When will ActiveRecord save associations?

后端 未结 2 1405
没有蜡笔的小新
没有蜡笔的小新 2021-02-03 18:32
  1. I know that it will save associations when autosave: true as per https://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-03 18:42

    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.

提交回复
热议问题