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

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.
6cf3e18ebc948992a4cbe83330496e36?d=identicon&s=25 Peter Jagielski (sweetpete)
on 2006-05-06 23:38
Guys,

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?
6cf3e18ebc948992a4cbe83330496e36?d=identicon&s=25 Peter Jagielski (sweetpete)
on 2006-05-06 23: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.
6ec1e89eef5ce09fbfa56be5b6dd17b5?d=identicon&s=25 Adam Bloom (admanb)
on 2006-05-07 06:03
What do your relationships look like?
6cf3e18ebc948992a4cbe83330496e36?d=identicon&s=25 Peter Jagielski (sweetpete)
on 2006-05-08 14:44
Adam,

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
columns.

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
records.

Here's the inspiration for all of the above:

http://tinyurl.com/kk5gt
This topic is locked and can not be replied to.