Mike
Mike

Reputation: 43

How do you save nested objects in rails 3?

I've been trying to find a solution to the following problem. I have three types of objects: A,B och C. C contains B and B contains A. What i wanna do is this:

A.new(:b = > B.new(:c => C.new)).save

but that failes, and I'm forced to do it the other way around. Any ideas on how I can write it? The current code looks like this:

  B.transaction do |t|
    b = B.create(:object => @object)
    C.create(:b => b)
  end

Upvotes: 3

Views: 1511

Answers (1)

apneadiving
apneadiving

Reputation: 115541

The best way to do this is to use accepts_nested_attributes_for.

You should put in model A:

accepts_nested_attributes_for :b_model

in model B:

accepts_nested_attributes_for :c_model

Then type:

params = { :a_model => {
               :name => 'i belong to a', 
               :b_attributes => {
                                 :title => 'I belong to b' 
                                 :c_attributes => {
                                                   :city => "I belong to c"
                                                  }
               }
            }
          }

a = AModel.create(params[:a_model])

See examples here.

Upvotes: 1

Related Questions