How to create nested objects using accepts_nested_attributes_for

后端 未结 4 704
我在风中等你
我在风中等你 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 01:58

    Ryan's solution is actually really cool. I went and made my controller fatter so that this nesting wouldn't have to appear in the view. Mostly because my view is sometimes json, so I want to be able to get away with as little as possible in there.

    class Product < ActiveRecord::Base
      has_many :notes
      accepts_nested_attributes_for :note
    end
    
    class Note < ActiveRecord::Base
      belongs_to :product
      validates_presence_of :product_id  unless :nested
      attr_accessor :nested
    end
    
    class ProductController < ApplicationController
    
    def create
        if params[:product][:note_attributes]
           params[:product][:note_attributes].each { |attribute| 
              attribute.merge!({:nested => true})
        }
        end
        # all the regular create stuff here  
    end
    end
    
    0 讨论(0)
  • 2021-02-04 02:09

    check this document if you use Rails3.

    http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#label-Validating+the+presence+of+a+parent+model

    0 讨论(0)
  • 2021-02-04 02:10

    Best solution yet is to use parental_control plugin: http://github.com/h-lame/parental_control

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题