How to create nested objects using accepts_nested_attributes_for

后端 未结 4 707
我在风中等你
我在风中等你 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
    

提交回复
热议问题