How to create nested objects using accepts_nested_attributes_for

后端 未结 4 703
我在风中等你
我在风中等你 2021-02-04 01:28

I\'ve upgraded to Rails 2.3.3 (from 2.1.x) and I\'m trying to figure out the accepts_nested_attributes_for method. I can use the method to update existing nested o

4条回答
  •  野性不改
    2021-02-04 02:11

    This is a common, circular dependency issue. There is an existing LightHouse ticket which is worth checking out.

    I expect this to be much improved in Rails 3, but in the meantime you'll have to do a workaround. One solution is to set up a virtual attribute which you set when nesting to make the validation conditional.

    class Note < ActiveRecord::Base
      belongs_to :product
      validates_presence_of :product_id, :unless => :nested
      attr_accessor :nested
    end
    

    And then you would set this attribute as a hidden field in your form.

    <%= note_form.hidden_field :nested %>
    

    That should be enough to have the nested attribute set when creating a note through the nested form. Untested.

提交回复
热议问题