开发者

What are the default values for Rails 3 for :dependent on has_many and belongs_to

In rails 3, i know that i can force deletion of dependent objects on b开发者_开发百科elongs_to and has_many relations using the :dependent => :delete option. However i was wondering,

what is the default behavior if i do not specify :dependent => ...

Cheers, Hajo


The documentation says, "When no option is given, the behavior is to do nothing with the associated records when destroying a record." That is, deleting or destroying an object will not delete or destroy the objects that it belongs to or has many of.


has_many uses the :nullify strategy, which will set the foreign to null. For has_many :through it will use delete_all.

For has_many, destroy will always call the destroy method of the record(s) being removed so that callbacks are run. However delete will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is :nullify (set the foreign keys to nil), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).

-- ActiveRecord::Associations::ClassMethods

Not sure exactly what belongs_to does, and wasn't able to find anything in the docs. I'll try to do some digging soon and update the answer.


In Rails 3, the default :dependent value is :nullify which sets foreign keys to nil.

The default strategy is :nullify for regular has_many. Also, this only works at all if the source reflection is a belongs_to.

Source: http://guides.rubyonrails.org/3_1_release_notes.html#active-record

This is still the case in Rails 4.

However delete and delete_all will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is :nullify (set the foreign keys to nil), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).

Source: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#module-ActiveRecord::Associations::ClassMethods-label-Delete+or+destroy%3F

Also see the source code docs: https://github.com/rails/rails/blob/b5a8fd7bb4a6fa4b67d4eabae4cea2cb1834d8d9/activerecord/lib/active_record/associations/collection_proxy.rb#L369

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜