我有一个继承自 ActiveRecord::Base 的 Commentable 类和一个继承自 Commentables 的 Event 类。
我已经覆盖了这两个类中的销毁方法,并且 Event.distroy 调用了 super。然而,一些意想不到的事情发生了。具体来说,事件的 has_and_belongs_to_many 关联被删除。我认为这是因为某些模块被包含在 Commentables 和 Event 类之间,但不确定是否有办法阻止这种情况。
这是简化的代码:
class Commentable < ActiveRecord::Base
has_many :comments
def destroy
comments.destroy_all
self.deleted = true
self.save!
end
end
class Event < Commentable
has_and_belongs_to_many :practitioners, :foreign_key => "commentable_id"
def destroy
#some Event specific code
super
end
end
我不想从数据库中删除行,只需设置一个“已删除”标志。我也不想删除任何关联。但是,在 Event.destroy 和 Commentable.destroy 之间的某个地方,其他一些 rails 代码会破坏 has_and_belongs_to_many 表中的记录。
知道为什么会发生这种情况以及如何阻止它吗?