Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 belongs_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

like image 724
fxtentacle Avatar asked Jun 26 '11 17:06

fxtentacle


People also ask

How does dependent destroy work?

dependent: :destroy Rails, when attempting to destroy an instance of the Parent, will also iteratively go through each child of the parent calling destroy on the child. The benefit of this is that any callbacks and validation on those children are given their day in the sun.

What is Activerecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


2 Answers

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.

like image 127
Rob Davis Avatar answered Oct 23 '22 13:10

Rob Davis


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.

like image 24
Blake Taylor Avatar answered Oct 23 '22 12:10

Blake Taylor