When will ActiveRecord save associations?

这一生的挚爱 提交于 2019-12-03 01:02:18

Unfortunately there are no such thing like associations_to_save. However there are some rules saying what is being saved when. You can find those here: http://guides.rubyonrails.org/association_basics.html. Points: 4.1.5 (belongs_to), 4.2.5 (has_one), 4.3.4 (has_many) and 4.4.4 (habtm).

UPDATE:

In case of has_many association, the child is saved on saving the parent if child.new_record? returns true (child was not yet saved to db), or the foreign_key column needs to be updated. This is why:

  1. Adding object to association on saved parent do save new child.
  2. Adding object to association on unsaved parent doesn't save (no foreign key value)
  3. If unsaved parent is being saved and has some child objects in association cache, those objects are saved to update foreign_key.

Not sure if this will help anyone else, but I recently ran into a similar issue recently in Rails 5.2.

When trying to save an object 2 layers deep my tests failed if the top level and the first level objects had already been saved. Ie.

book_cover.persisted? == true
book_cover.book.persisted? == true

page = book_cover.book.pages.new

page.persisted? == false

# After saving the top level object
book_cover.save
page.persisted? == false

# After saving the immediate parent of page
book_cover.book.save
page.persisted? == true

Since the parent "book cover" wasn't the direct parent of the new object "page" saving "book cover" didn't actually end up saving the "page" object.

Depending on the situation I just explicitly called save on the "book" object to save all the child objects.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!