2012-10-03 56 views
0

我有一個模型:破壞belongs_to的離開FK

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沒有關聯。

當我這樣做:

merchant.billing_address.destroy 

在數據庫中,該地址記錄了,但merchants.billing_address_id保持一個假值。這是mysql,所以沒有參照完整性。

我在做什麼錯?

注意:我知道這可能更好地模擬爲has_one關聯。我可能不得不去那裏,但我寧願不去。

更新:增加了一些代碼來顯示多個地址關聯。

回答

0

原來,ActiveRecord不支持單向belongs_to關聯,unlike other ORMs I've worked with。但是你可以自己破解它,像這樣:

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