Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know how to work has_many :posts, dependent: :destroy. If User or something that has_many posts is destroyed, all belonging posts are also destroyed.

But what happens when Post model belongs_to :user, dependent: :destroy? I found the option in Rails Guide, but I couldn't find out how to work it.

http://guides.rubyonrails.org/association_basics.html

like image 896
ironsand Avatar asked Jan 06 '16 02:01

ironsand


1 Answers

"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: :destroy
end

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: :destroy
end

Student Model

class Student < ActiveRecord::Base
    belongs_to :teacher, dependent: :destroy
end 

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.

like image 80
JohnSalzarulo Avatar answered Oct 18 '22 04:10

JohnSalzarulo