Non-tech founder’s guide to choosing the right software development partner Download Ebook
Home>Blog>How to delete polymorphic models cascade

How to delete polymorphic models cascade

If you use a polymorphic model in your Rails application, like in example


class Trade < ActiveRecord::Base

  has_many :gl_entries, as: :source, dependent: :destroy

end



class GlEntry < ActiveRecord::Base

  belongs_to :source, polymorphic: true

end

You will not be able to add the usual foreign keys for cascading delete records. But this can be implemented using a database.

To do this, you need to write a trigger in the database that will run the delete function for each record.


CREATE FUNCTION deleteGlEntriesOfTrade()

  RETURNS TRIGGER

  SET SCHEMA 'public'

  LANGUAGE plpgsql 

  AS $$

  BEGIN

    DELETE FROM gl_entries WHERE source_id = OLD.id AND source_type = 'Trade';

    RETURN OLD;   

  END;

  $$;



CREATE TRIGGER deleteTradesGlEntriesTrigger 

  BEFORE DELETE ON trades

  FOR EACH ROW EXECUTE PROCEDURE deleteGlEntriesOfTrade();

Create a migration and use :)

Discover More Reads

Categories:

Recent Projects

We take pride in creating applications that drive growth and evolution, from niche startups to international companies.

Let’s Build Something Great Together

Let’s discuss your project and see how Ruby on Rails can be your competitive advantage.

*By submitting this form, you agree with JetRockets’ Privacy Policy