Bidirectional Destroys in Rails 5

Posted by : on

Category : Rails

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.



About Ram Laxman Yadav
Ram Laxman Yadav

Senior Software Engineering Professional | Tech Enthusiast | Mentor | Payments | Hospitality | E-Commerce, based in NCR, India

Email : info@ramlaxman.co.in

Website : https://ramlaxman.co.in