开发者

Has many relationship in rails

开发者 https://www.devze.com 2023-01-05 20:17 出处:网络
I have this relationship in a Rails app class Folder has_many :elements end class Element belongs_to :folder

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(...)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号