Rails 5 +嵌套属性,其中has_one在创建时具有错误

Muk*_*esh -1 nested ruby-on-rails

我的标准代码

class Bank < ApplicationRecord
    has_one :address
    accepts_nested_attributes_for :address
end



 class Address < ApplicationRecord
    belongs_to :bank
 end
Run Code Online (Sandbox Code Playgroud)

我的控制器

def create
    @bank = Bank.new(bank_params)

    respond_to do |format|
      if @bank.save
        format.html { redirect_to @bank, notice: 'Bank was successfully created.' }
        format.json { render :show, status: :created, location: @bank }
      else
        format.html { render :new }
        format.json { render json: @bank.errors, status: :unprocessable_entity }
      end
    end
end

def bank_params
      params.require(:bank).permit(:code, :currency, :name, :mobile_1, :mobile_2, :email, address_attributes: [:id, :name, :area, :pin_code, :city_id] )
end
Run Code Online (Sandbox Code Playgroud)

它给出了类似的错误

@messages = {:"address.bank"=> ["必须存在"]},@ details = {"address.bank"=> [{:error =>:blank}

为什么它反过来......不理解

ore*_*uwa 6

我确定这是因为你的地址模型已经验证了银行.鉴于观察结果,我认为Rails会尝试:

validate your parent model
validate your child model # validation fails here because parent doesn't have an id yet, because it hasn't been saved
save parent model
save child model
Run Code Online (Sandbox Code Playgroud)

但是,我认为您应该能够通过使用如下:inverse_of选项来解决这个问题:

class Bank < ApplicationRecord
    has_one :address, inverse_of: :bank
    accepts_nested_attributes_for :address
end

class Address < ApplicationRecord
  belongs_to :bank, inverse_of: :address
  validates :bank, presence: true
end
Run Code Online (Sandbox Code Playgroud)

如果这对您有用,请告诉我

  • 这是因为Rails 5更改了`belongs_to`关联以将`required`属性设置为默认为`true`.你需要`inverse_of`,以便Rails可以正确地找出相关的模型.http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html (6认同)
  • `:inverse_of`选项主要用于优化。它基本上说要引用内存对象以进行关联。这是必需的,因为在验证子模型时,默认情况下未保存关联的对象,并且关联的对象不引用内存中的对象。 (2认同)