Forum: Ruby on Rails deleting all related tuples in all relevant tables

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6f4b47640cb2bcb8624ecdd532aba783?d=identicon&s=25 Gilles (Guest)
on 2007-01-09 00:16
So I have three tables, table_a, table_c, and table_u.

both table_c and table_u reference table_a

so basically these three tables are related

If I delete an entry in table_a, I want all entries in table_c and
table_u that reference table_a deleted as well.

Is there a way to do this? What does the code look like to do something
like this?

Thanks!

Gilles
Aedb187f1ebbbc22557ade4003869afd?d=identicon&s=25 jdswift (Guest)
on 2007-01-09 00:23
(Received via mailing list)
I think you just want something like:

  has_many :things, :dependent => :destroy

in your model.
67f61f0c385168c4b2e5b8fd733c397f?d=identicon&s=25 Christos Zisopoulos (Guest)
on 2007-01-09 00:54
(Received via mailing list)
I am assuming that you also have the three classes that correspond to
the tables set up with a has_many relationship...

So,

  def Table_a < ActiveRecord::Base
   has_many :table_as, :dependent => :destroy
   has_many :table_us, dependent => :destroy
  end

  def Table_b < ActiveRecord::Base
   belongs_to :table_a
  end

  def Table_u < ActiveRecord::Base
   belongs_to :table_a
  end

The :dependent => :destroy is all you need in order to be able to do...

  Table_a.find(:first).destroy

...and have all Table_u and Table_c entries that reference the first
entry in Table_a destroyed.

Have a look at the options here:

http://api.rubyonrails.org/classes/ActiveRecord/As...
ClassMethods.html#M000530

-christos
This topic is locked and can not be replied to.