[英]RAILS: Nested attributes in new method with existing record
I have models: 我有模特:
Frame.rb Frame.rb
belongs_to :manufacturer, foreign_key: 'model'
accepts_nested_attributes_for :manufacturer, :reject_if => proc { |obj| obj.blank? }
When i try to create new Frame with existing manufacturer i get an error: 当我尝试使用现有制造商创建新框架时,我收到错误:
Frame.new({name: 'Name of the frame', manufacturer_attributes: {id:2}})
Error: 错误:
Couldn't find Manufacturer with ID=2 for Frame with ID=
The problem is that Frame.new
is a new record, when ActiveRecord reaches the parameter manufacturers_attributes
it performs a lookup on the association manufacturers_attributes
for Frame.new
which is unsaved and hence has no id with which to perform the lookup. 问题是
Frame.new
是一个新记录,当ActiveRecord到达参数manufacturers_attributes
它对Frame.new
的关联manufacturers_attributes
执行查找,这是未保存的,因此没有用于执行查找的id。
I recommend starting with the existing manufacturer
record and simply create the frame like so manufacturer.frames.create(frame_params)
(assuming a one-to-many relationship). 我建议从现有的
manufacturer
记录开始,然后简单地创建像manufacturer.frames.create(frame_params)
这样的框架(假设一对多的关系)。
However, if you must do it this way you can overwrite the manufacturer_attributes
method like so: 但是,如果必须这样做,则可以覆盖
manufacturer_attributes
方法,如下所示:
accepts_nested_attributes_for :manufacturer
def manufacturer_attributes=(attributes)
if attributes['id'].present?
self.manufacturer = Manufacturer.find(attributes['id'])
end
super
end
Thus, you assign the manufacturer before the original manufacturer_attributes
tries to access it on the new record, which previously caused the error. 因此,您在原始
manufacturer_attributes
尝试在新记录上访问它之前分配制造商,该记录先前导致了错误。
If you want a new Frame with an existing manufacturer you need to assign it in the params as well as using nested attributes. 如果您想要一个具有现有制造商的新框架,您需要在参数中分配它以及使用嵌套属性。
Frame.new({name: 'Name', manufacturer_ids: [2], manufacturer_attributes: {id:2}})
The new Frame now has the assigned Manufacturer so when it attempts to update the Manufacturer with the manufacturer_attributes
it can find it correctly. 新框架现在具有指定的制造商,因此当它尝试使用
manufacturer_attributes
更新制造商时,它可以正确找到它。
If you only want to assign the existing Manufacturer and not update any attributes then you don't need the manufacturer_attributes
. 如果您只想分配现有的制造商而不更新任何属性,那么您不需要
manufacturer_attributes
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.