RAILS: Nested attributes in a new method with an existing record

I have models:

Frame.rb

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

When I try to create a new Frame with an existing manufacturer, I get an error message:

Frame.new({name: 'Name of the frame', manufacturer_attributes: {id:2}})

Error:

Couldn't find Manufacturer with ID=2 for Frame with ID=
+2
source share
2 answers

The problem is what Frame.newis the new record, when ActiveRecord reaches the parameter manufacturers_attributes, it searches for an association manufacturers_attributesfor Frame.new, which is unsaved and therefore does not have an identifier with which to search.

I recommend starting with an existing record manufacturerand simply creating such a frame manufacturer.frames.create(frame_params)(assuming a one-to-many relationship).

, , 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 , .

+3

, , .

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

Frame , , manufacturer_attributes, .

- , manufacturer_attributes.

+2

Source: https://habr.com/ru/post/1502478/


All Articles