【发布时间】:2014-06-06 20:19:40
【问题描述】:
将现有的项目模型添加到新的付款模型时,会出现错误“找不到 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
...
付款和项目模型是假设的,但问题是真实的。在保存付款(在创建操作中完成)之前,我需要将项目与付款相关联(就像我在新操作中所做的那样)。用户需要在创建付款时修改项目的属性(例如添加帐单代码)。
具体来说,错误发生在控制器的创建动作中:
# 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,我愿意接受建议。
【问题讨论】:
-
嘿,我认为您应该修改您的 payment_params 以允许 item_attributes 中的 :id 像这样:
params.require(:payment).permit( ..., [items_attributes: [:id, :billcode]])。这样,可以从数据库中提取正确的可用项目。让我知道这个是否奏效。 ` -
哦,你是对的。它在我的代码中只是不是这个问题。您可以在传递回来的 params 哈希中看到它。我将修复代码 sn-p。非常感谢您能理解这一点。
-
您的
payment_id中的items是否正确保存? -
它永远不会走那么远。发生错误时,付款模型仍然是新记录。
-
看起来类似于this
标签: ruby-on-rails activerecord ruby-on-rails-4