问题描述
1)我知道,这将节省协会当自动保存:真正的
按http://railsapi.com/doc/rails-v2.3.8/classes/ActiveRecord/AutosaveAssociation.html
1) I know that it will save associations when autosave: true
as per http://railsapi.com/doc/rails-v2.3.8/classes/ActiveRecord/AutosaveAssociation.html
2)我知道,这将节省的构造像
2) I know that it will save associations that are constructed like
book = Book.new(name: 'foo')
book.authors.build(name: 'bar') #has_many
book.save
或如
book = Book.new(name: 'foo')
book.build_author(name: 'bar') #has_one
book.save
3)我认为协会也保存他们被分配或添加时
3) I think associations are also saved when they are assigned or added
book = Book.new(name: 'foo')
book.author = Author.new(name: 'bar')
book.save
或
book = Book.new(name: 'foo')
book.authors << Author.new(name: 'bar')
book.save
不过,我有一个涉及到的东西不会自动保存时,我希望到一个复杂的问题。所以,我想通过检查书
来验证我的想法是要保存实际上将被保存到调试。
But, I have a complicated bug that involves something not auto-saving when I would expect it to. So, I want to debug by inspecting book
to verify what I think is going to be saved will actually be saved.
TL; DR;节能协会在什么样的内部状态进行检查?我假设一个模型具有像内部的实例变量associations_to_save
的关联被添加到在创建时。然后,当模型保存,它遍历这些关联并保存它们。
TL; DR;What internal state is checked when saving associations? I'm assuming that a model has an internal instance variable like associations_to_save
that associations get added to when they are created. Then, when the model is saved, it loops through those associations and saves them too.
推荐答案
不幸的是没有这样的事就像associations_to_save。但也有一些规则,说什么被保存时。你可以找到那些在这里:http://guides.rubyonrails.org/association_basics.html.要点:4.1.5(belongs_to的),4.2.5(HAS_ONE),4.3.4(的has_many)和4.4.4(HABTM)
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).
更新:
在案件的has_many协会,孩子被保存在拯救父母,如果child.new_record?返回true(子尚未保存到分贝),或foreign_key列需要更新。这就是为什么:
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:
- 添加对象的关联上保存的父母确实保存新的孩子。
- 添加对象关联的未保存的父母不保存(无外键值)
- 如果未保存的父母被保存,并在协会缓存一些子对象,这些对象被保存到更新foreign_key。
这篇关于当将ActiveRecord的节省联想?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!