Bidirectional Destroys in Rails 5 | Ram Laxman Yadav

Bidirectional Destroys in Rails 5

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
    class Author < ApplicationRecord
        has_one :book, dependent: :destroy
 #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.


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

Ram Laxman Yadav
Ram Laxman Yadav
Ruby on Rails Developer