如何验证嵌套属性?

时间:2018-05-22 22:17:32

标签: ruby-on-rails

我有一个表单,它使用嵌套的地址创建一个新属性。问题是没有对“地址”进行验证。当我把所有表格都留空时。这就像系统从不读取地址模型验证,我甚至可以创建一个新属性而不填写地址。

我有以下型号:

property.rb:

class Property < ApplicationRecord
 has_one :address
 accepts_nested_attributes_for :address
end

address.rb:

class Address < ApplicationRecord
  belongs_to :property
  validates :state, :city, presence: true
end

property_controller.rb:

  def new
    @property = Property.new
    @property.build_address
  end

  def create
    @property = current_user.properties.build(property_params)
    respond_to do |format|
      if @property.save
        format.html { redirect_to @property, notice: 'Property was successfully created.' }
      else
        format.html {
             @property.build_address #nedded to show the address inputs again
             render :new }
      end
    end
  end

1 个答案:

答案 0 :(得分:0)

仔细检查代码我发现如果我发送至少一个参数作为嵌套表单(例如:city)并从@property.build_address操作中删除create,则一切正常。

相关问题