Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using Dependent Destroy In Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 794
    Comment on it

    As we know that all the models in our rails application are connected to one another through relations between them.

    Now these relations can be one to one, many to many, many to one or one to many and etc.

    Now lets see a scenario where we have an article model and a tag model. Both the article and tag model are connected to each other with many to many relationship.

    class Article < ActiveRecord::Base
        
         has_many :taggings, dependent: :destroy
         has_many :tags , through: :taggings
     
    end
    class Tag < ActiveRecord::Base
    
      has_many :taggings, dependent: :destroy
      has_many :articles, through:  :taggings
    
    end

    Now we create a third model taggings which is acting as a junction table between article and tag model.

    class Tagging < ActiveRecord::Base
        
      belongs_to :tag
      belongs_to :article
    
    end

    This tagging table has one to one relationship with both the article and tag model because it has got primary keys of both the tables.

    Now lets suppose that the publisher of the article deletes his article. So in that case the article would be removed from the articles table, but the junction table taggings still have the ID of that article and the corresponding tag IDs.

    So ethically same should get deleted too so that there should be no database errors later and memory consumption.

    So for this rails provide us with a method dependent: :destroy.  Dependent destroy destroys all the corresponding entries in all the tables where the deleted article's ID is present. 

    All we have to do is write dependent: :destroy ahead of all those associations where we want the article's relations and entries be deleted from other tables.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: