Tim Scott
Tim Scott

Reputation: 15205

destroy belongs_to leaves FK

I have a model:

class Merchant < ActiveRecord::Base
    belongs_to :billing_address, class_name: Address, dependent: :destroy
    belongs_to :other_address1, class_name: Address, dependent: :destroy
    belongs_to :other_address2, class_name: Address, dependent: :destroy
    belongs_to :other_address3, class_name: Address, dependent: :destroy
    belongs_to :other_address4, class_name: Address, dependent: :destroy
    ...
end

Address has no associations.

When I do this:

merchant.billing_address.destroy

In the database, the address record is gone, but merchants.billing_address_id keeps a bogus value. This is mysql, so no referential integrity.

What am I doing wrong?

NOTE: I realize this might be better modeled as a has_one association. I might have to go there, but I prefer not to.

UPDATE: Added a little more code to show the multiple Address associations.

Upvotes: 1

Views: 761

Answers (2)

konyak
konyak

Reputation: 11706

If you want merchant.billing_address to be null after you destroy the billing address, then you need to use :dependent => :nullify in the Address model.

Ref http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Upvotes: 2

Tim Scott
Tim Scott

Reputation: 15205

It turns out that ActiveRecord does not support one-sided belongs_to associations, unlike other ORMs I've worked with. But you can hack it yourself like so:

before_save :remove_ids_for_nil_associations

def remove_ids_for_nil_associations
  self.billing_address_id = nil if is_getting_destroyed? self.billing_address
  ...
end

def is_getting_destroyed?(ref)
  ref.present? && ref.destroyed?
end

Upvotes: 0

Related Questions