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
开发者_StackOverflow中文版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.
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(...)
精彩评论