Foreign key on_delete: :cascade - when parent is deleted delete a child
Rails
PostgreSQL
When you add a foreign key with on_delete: :cascade, you’re telling the database:
“If the parent record is deleted, automatically delete all related child records too.”
class CrePartyRepresentingClients < ActiveRecord::Migration[7.2] def change create_table :party_representing_clients do |t| t.references :party, null: false, foreign_key: {on_delete: :cascade} t.references :client, null: false, foreign_key: {to_table: :parties, on_delete: :cascade} t.timestamps end end end
add_foreign_key :party_representing_clients, :parties, column: :party_id, on_delete: :cascade add_foreign_key :party_representing_clients, :parties, column: :client_id, on_delete: :cascade