如何触发属于自动删除该对象的连接模型一部分的对象的销毁回调?
轨道 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
我的问题是,当订阅由于加入模型而自动删除时,如何触发此回调?
Rails 2.3.8. I have 3 models, User, Source, and 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
I have an interface that allows a User to edit their Subscriptions to a Source. It collects source_ids, and creates or deletes a Subscription based on the collection. The problem I am having is, quote:
"Automatic deletion of join models is direct, no destroy callbacks are triggered."
The Subscriptions are being deleted, not destroyed. I have a callback in the Subscription model that is not triggered:
before_destroy do |subscription|
[Some irrelevant object not to be mentioned].destroy
end
My question is, how can I trigger this callback when a Subscription is automatically deleted due to the join model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
回复您在HMT collection_singular_ids=删除连接模型是直接的,不会触发销毁回调中的
回复将此行:更改
为:
并且在用户模型中定义受保护的 your_custom_method 。这样,当用户删除某个源的订阅时,就会调用此方法。
祝你好运!
Replying to your reply in HMT collection_singular_ids= deletion of join models is direct, no destroy callbacks are triggered
Change this line:
To this:
And define protected your_custom_method in User model. This way when a user removes a Subscription to some Source, this method gets called.
Good luck!
来自 rdoc:
collection.delete(object, …)
通过将外键设置为 NULL 来从集合中删除一个或多个对象。如果对象与
:dependent => 关联,则它们也会被销毁。 :destroy
,如果与:dependent => 关联则删除:删除全部
From the rdoc:
collection.delete(object, …)
Removes one or more objects from the collection by setting their foreign keys to
NULL
. Objects will be in addition destroyed if they’re associated with:dependent => :destroy
, and deleted if they’re associated with:dependent => :delete_all