DEV Community

Dmitry Voronov for JetRockets

Posted on • Edited on • Originally published at jetrockets.pro

3 1

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Create a migration and use :)

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay