RAILS: Nested attributes in new method with existing record

后端 未结 2 1759
野性不改
野性不改 2021-01-05 07:00

I have models:

Frame.rb

belongs_to :manufacturer, foreign_key: \'model\'
accepts_nested_attributes_for :manufacturer, :reject_if =&g         


        
2条回答
  •  半阙折子戏
    2021-01-05 07:57

    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.

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

    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
    

    Thus, you assign the manufacturer before the original manufacturer_attributes tries to access it on the new record, which previously caused the error.

提交回复
热议问题