RAILS:具有现有记录的新方法中的嵌套属性

我有模特:

Frame.rb

belongs_to :manufacturer, foreign_key: 'model' accepts_nested_attributes_for :manufacturer, :reject_if => proc { |obj| obj.blank? } 

当我尝试使用现有制造商创建新框架时,我收到错误:

 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。

我建议从现有的manufacturer记录开始,然后简单地创建像manufacturer.frames.create(frame_params)这样的框架(假设一对多的关系)。

但是,如果必须这样做,则可以覆盖manufacturer_attributes方法,如下所示:

 accepts_nested_attributes_for :manufacturer def manufacturer_attributes=(attributes) if attributes['id'].present? self.manufacturer = Manufacturer.find(attributes['id']) end super end 

因此,您可以在原始manufacturer_attributes尝试在新记录上访问它之前分配制造manufacturer_attributes ,而新记录之前会导致错误。

如果您想要一个具有现有制造商的新框架,您需要在参数中分配它以及使用嵌套属性。

 Frame.new({name: 'Name', manufacturer_ids: [2], manufacturer_attributes: {id:2}}) 

新框架现在具有指定的制造商,因此当它尝试使用manufacturer_attributes更新制造商时,它可以正确找到它。

如果您只想分配现有的制造商而不更新任何属性,那么您不需要manufacturer_attributes