views:

44

answers:

1

Hi all,

I have this relationship in a Rails app

class Folder
  has_many :elements
end

class Element
  belongs_to :folder
end

My problem is this code doesn't work

element = Element.first
a_folder.elements << element
element.save!
a_folder.save!

, but this one works:

element.folder = a_folder
element.save!

Anyone can tell me why?

Thanks.

+4  A: 

From the Rails documentation

Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object (the owner of the collection) is not yet stored in the database.

So if @folder is already saved then @folder.elements << @element should work.

You can also add elements like this:

@folder.elements.create(...)
bjg
@folder.elements.create(...) is an excellent and clear way to do this
Jimmy
I really like @folder.elements.create(...)This error only appears on unit tests. The fixtures are wrong :(Thank you, bjg
pablorc