Friday, September 19, 2008

belongs_to :dependent => :destroy with foreign key constraints

Moved here

I discovered what I believe to be a bug in activerecord (2.1.0) today. If you have something like the following:
class Person < ActiveRecord::Base
  belongs_to :person_address, :dependent => :destroy
end

class PersonAddress < ActiveRecord::Base
  has_one :person
end

...and you have for foreign key constraint on person_address_id on the person table to id on the person_address table (which would be a reasonable thing to do) you will get a foreign key constraint error when you try to destroy a person record (if the associated person_address record exists). I submitted a patch to rails for this, but in the meantime, I found this as a work around:
class Person < ActiveRecord::Base
  belongs_to :person_address # note: no :dependent => :destroy

  def destroy
    super() # first destroy ourselves before we destroy the association
    PersonAddress.destroy(self.person_address_id) if self.person_address_id
  end
end

No comments: