How it works - `belongs_to :user, dependent: :destroy` How it works - `belongs_to :user, dependent: :destroy` ruby ruby

How it works - `belongs_to :user, dependent: :destroy`


"has_many" 

A teacher "has_many" students. Every student has only one teacher, but every teacher has many students. This means that there is a foreign key, or teacher_id on the student referencing to what teacher they belong to.

"belongs_to" 

A student "belongs_to" a teacher. Every teacher has many students, but every student has only one teacher. Again, there is the foreign key on the student referencing to what teacher they belong.

Let's work this out an using this student / teacher concept.

Teacher Model

class Teacher < ActiveRecord::Base  has_many :students, dependent: :destroyend

Student Model

class Student < ActiveRecord::Base    belongs_to :teacher end 

Assuming these models then

Teacher.destroy 

Will delete the instantiated teacher and all the students that were associated to that teacher.

For example

Teacher.find(345).destroy 

Would destroy the record of the teacher with the ID of 345 and destroy all the associated students with that teacher.

Now to the heart of the question, what happens when my models look like this?

Teacher Model

class Teacher < ActiveRecord::Base  has_many :students, dependent: :destroyend

Student Model

class Student < ActiveRecord::Base    belongs_to :teacher, dependent: :destroyend 

If I were to call

Student.destroy

This would destroy the instantiated student and that student's associated teacher. However to my knowledge (and according to the docs) this would not destroy any other students related to that teacher, leaving them 'orphaned'.

Here is a quote from the Ruby docs on this 1

If set to :destroy, the associated object is destroyed when this object is. This option should not be specified when belongs_to is used in conjunction with a has_many relationship on another class because of the potential to leave orphaned records behind.


It instantiates an instance of all of the users then sends the message destroy to each. Results in normal destruction lifecycle for the users that are destroyed this way.


I have try set dependent: :destroy into belongs_to. Example

class Post < ActiveRecord::Base  has_many :comments, dependent: :destroyendclass Comment < ActiveRecord::Base  belongs_to :post, dependent: :destroyend

In a console, if comment has been destroy, post will be destroyBut I think you shouldn't set belongs_to + dependent: :destroy together

In fact, example on facebook, when 1 comment of 1 post has been deleted, this post will not be deleted