RAILS:具有现有记录的新方法中的嵌套属性 [英] RAILS: Nested attributes in new method with existing record
问题描述
我有模型:
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}})
错误:
Couldn't find Manufacturer with ID=2 for Frame with ID=
推荐答案
问题是Frame.new
是一条新记录,当ActiveRecord到达参数manufacturers_attributes
时对 Frame.new
的关联 manufacturers_attributes
执行查找,该关联未保存,因此没有用于执行查找的 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.
我建议从现有的 manufacturer
记录开始,然后像这样简单地创建框架 manufacturer.frames.create(frame_params)
(假设是一对多关系).
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_attributes
方法:
However, if you must do it this way you can overwrite the manufacturer_attributes
method like so:
accepts_nested_attributes_for :manufacturer
def manufacturer_attributes=(attributes)
if attributes['id'].present?
self.manufacturer = Manufacturer.find(attributes['id'])
end
super
end
因此,您可以在原始 manufacturer_attributes
尝试访问新记录上的制造商之前分配制造商,这在之前导致了错误.
Thus, you assign the manufacturer before the original manufacturer_attributes
tries to access it on the new record, which previously caused the error.
这篇关于RAILS:具有现有记录的新方法中的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!