如何触发销毁回调以删除自动删除该对象的连接模型中的对象?

8
Rails 2.3.8。我有三个模型,用户(User),资源(Source)和订阅(Subscription)。
User  attr_accessible   :source_ids
             has_many   :subscriptions
             has_many   :sources, :through => :subscriptions

Source       has_many   :subscriptions

Subscription belongs_to :user
             belongs_to :source

我有一个接口,允许用户编辑他们对某个资源的订阅。它会收集资源ID,并根据收集的结果创建或删除订阅。但现在遇到了一个问题:

"自动删除连接模型是直接的,不会触发destroy回调函数。"

订阅记录被删除了,而非销毁。我在订阅模型中设置了回调函数,但该函数并没有被触发:

before_destroy do |subscription|
  [Some irrelevant object not to be mentioned].destroy
end

我的问题是,当订阅由于加入模型而被自动删除时,我如何触发此回调函数?
2个回答

7

your_custom_method 应该在使用 after_remove 的同一个文件中定义,而不是像你描述的那样在“用户模型”中定义。 - Joshua Pinter

2
@user.subscriptions.delete
has_many   :subscriptions, :dependent => :destroy    # <- setting this on the association  will destroy the related subscriptions
has_many   :subscriptions, :dependent => :delete_all # <- setting this on the association  will delete the related subscriptions

根据rdoc文档:

collection.delete(object, …)
通过将对象的外键设置为NULL,从集合中删除一个或多个对象。如果这些对象与:dependent => :destroy相关联,则它们将被额外销毁;如果它们与:dependent => :delete_all相关联,则它们将被删除。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接