Forum: Ruby on Rails Question about one-to-many-to-many

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Peter J. (Guest)
on 2006-05-07 01:38

I've set up a 1-M-M relationship between 3 tables/models.  I can't get
cascading deletes (haven't tried updates yet) to work when the master
record is deleted.  I'm using MySQL 4.1.x, and the error message is:

Mysql::Error: #23000Cannot delete or update a parent row: a foreign key
constraint fails: DELETE FROM contact_addresses WHERE (contact_id = 1).

Is this something that's not supported by MySQL?  Or might I have setup
my models (has_many, belongs_to, etc.) incorrectly?
Peter J. (Guest)
on 2006-05-07 01:52
Oops, forgot to mention - the error above is referring to the 1st M
table.  What I believe is obviously happening is that the master record
in the 1st M table is being deleted, but it can't because there are
child records still in the 2nd M table.
Adam B. (Guest)
on 2006-05-07 08:03
What do your relationships look like?
Peter J. (Guest)
on 2006-05-08 16:44

Logically speaking, a contact can have multiple addresses, and each
address can have multiple phone numbers:

Contact (master):

  has_many :contact_addresses, :dependent => :delete_all

ContactAddress (detail 1):

  belongs_to :contact
  has_many   :addresses_phones, :dependent => :delete_all
  has_many   :contact_phones,   :through => :addresses_phones

ContactPhone (detail 2):

  belongs_to :contact_addresses
  has_many :addresses_phones,  :dependent => :delete_all
  has_many :contact_addresses, :through => :addresses_phones

The addresses_phones table (which links addresses and phones) is not in
the model, and simply contains contact_address_id and a contact_phone_id

I'm wondering if I need to write a line or 2 of code that first deletes
the phone records so that Rails can then delete the address and contact

Here's the inspiration for all of the above:
This topic is locked and can not be replied to.