8

导轨 2.3.8。我有 3 个模型,用户、源和订阅。

User  attr_accessible   :source_ids
             has_many   :subscriptions
             has_many   :sources, :through => :subscriptions

Source       has_many   :subscriptions

Subscription belongs_to :user
             belongs_to :source

我有一个界面,允许用户编辑他们对源的订阅。它收集 source_ids,并基于该集合创建或删除订阅。我遇到的问题是,引用:

“连接模型的自动删除是直接的,不会触发销毁回调。”

订阅正在被删除,而不是被销毁。我在订阅模型中有一个未触发的回调:

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

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

4

2 回答 2

7

在 HMT collection_singular_ids= 中回复您的回复删除连接模型是直接的,不会触发销毁回调

更改此行:

 has_many :users, :through => :memberships

对此:

 has_many :users, :through => :memberships, :after_remove => :your_custom_method

并在用户模型中定义受保护的 your_custom_method。这样,当用户删除某个源的订阅时,就会调用此方法。

祝你好运!

于 2011-01-31T00:45:43.207 回答
3
@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

于 2011-01-29T23:52:56.857 回答