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}
为什么它反过来......不理解
我确定这是因为你的地址模型已经验证了银行.鉴于观察结果,我认为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)
如果这对您有用,请告诉我
| 归档时间: |
|
| 查看次数: |
2681 次 |
| 最近记录: |