Ram Laxman Yadav bio photo

Ram Laxman Yadav

Ruby on Rails Developer

Email Twitter LinkedIn Github Stackoverflow

Suppose you have two models having has_many/belongs_to associations between them, In previous versions of rails you cannot add dependent: :destroy to both of the relationships statements. Attempting to delete either of these records results in a circular dependency, with each record attempting to delete the other one, ending in a Stack Too Deep error. Rails 5 has addressed this issue and it is now possible to have models with has/belongs_to relationship with dependent: :destroy in both models. Here is an example:

    class Book < ApplicationRecord
        belongs_to :author, dependent: :destroy
    end
    class Author < ApplicationRecord
        has_one :book, dependent: :destroy
    end
 #Now, if you have an Entry record that has a related Position record, deleting either of the records will result in the deletion of the related record.

Summary

Although it is very powerfull feature but be carefull to write dependent: :destroy in both models, because it deleted both records.