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

时间:2016-07-17 18:49:27

标签: ruby-on-rails nested

我的模型代码

class Bank < ApplicationRecord
    has_one :address
    accepts_nested_attributes_for :address
end



 class Address < ApplicationRecord
    belongs_to :bank
 end

我的控制器

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

它给出了类似的错误

@messages = {:&#34; address.bank&#34; =&gt; [&#34;必须存在&#34;]},@ details = {&#34; address.bank&#34 ; =&GT; [{:误差=&GT;:空白}

为什么它表现出反向......不理解

2 个答案:

答案 0 :(得分: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

但是,我认为您应该可以使用: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

让我知道这是否适合您

答案 1 :(得分:2)

Rails 5默认需要belongs_to关联

By using (optional: true), we can change behavior 

class Bank < ApplicationRecord
    has_one :address, optional: true
    accepts_nested_attributes_for :address
end



 class Address < ApplicationRecord
    belongs_to :bank, optional: true
 end