将现有的项目模型添加到新的付款模型时,会出现错误“无法找到 ID=123 的付款项目 ID=”。这是在 has_many 关系中并使用 accepts_nested_attributes_for。
class Payment < ActiveRecord::Base
has_many :items
accepts_nested_attributes_for :items
...
class Item < ActiveRecord::Base
belongs_to :payment
...
付款和项目模型是假设的,但问题是真实的。在保存付款(在创建操作中完成)之前,我需要将项目与付款相关联(就像我在新操作中所做的那样)。用户需要在创建付款时修改项目的属性(例如添加账单代码)。
具体来说,错误发生在 Controller 的创建 Action 中:
# payments_controller.rb
def new
@payment = Payment.new
@payment.items = Item.available # where(payment_id: nil)
end
def create
@payment = Payment.new payment_params # <-- error happens here
...
end
def payment_params
params.require(:payment).permit( ..., [items_attributes: [:id, :billcode]])
end
lib/active_record/nested_attributes.rb:543:in 'raise_nested_attributes_record_not_found!'
在调用堆栈中紧接在它之前。奇怪的是,ActiveRecord 将payment_id 作为搜索条件的一部分。为了完整起见,表格看起来像这样......
form_for @payment do |f|
# payment fields ...
fields_for :items do |i|
# item fields
并且它在新操作上正确呈现项目。通过表单传递的参数如下所示:
{ "utf8"=>"✓",
"authenticity_token"=>"...",
"payment"=>{
"items_attributes"=>{
"0"=>{"billcode"=>"123", "id"=>"192"}
},
}
}
如果有更好的方法来解决这个问题而不使用
accepts_nested_attributes_for
我愿意接受建议。
最佳答案
我只需添加一个 item_ids
就可以使用它参数集合(除了 items_attributes
)。您应该能够在 Controller 中按摩您的参数,使其看起来像这样
{ "utf8"=>"✓",
"authenticity_token"=>"...",
"payment"=>{
"item_ids"=>[192]
"items_attributes"=>{
"0"=>{"billcode"=>"123", "id"=>"192"}
},
}
}
更新 1:出于某种原因,这只适用于
item_ids
之前 items_attributes
在哈希中。还没有评论Rails docs还没有弄清楚原因。
关于ruby-on-rails - 使用 accepts_nested_attributes_for 将现有的 has_many 记录添加到新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090024/