Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 467
Mike Avatar asked Sep 10 '26 16:09

Mike


1 Answers

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.

like image 146
apneadiving Avatar answered Sep 13 '26 15:09

apneadiving