我有一个模特:
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 :(得分:2)
如果您希望在销毁帐单邮寄地址后Merchant.billing_address为空,则需要在地址模型中使用:dependent => :nullify
。
参考http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
答案 1 :(得分: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