Rails中的after_destroy回调顺序 [英] after_destroy callback order in Rails
问题描述
我正在使用PostgreSql作为数据库以及Rails 3.1.3和ruby 1.9.3我有3个模型.
I am using PostgreSql as database and Rails 3.1.3 and ruby 1.9.3 I have 3 models.
-
活动
-
ActivityObject
-
ActivityObjectActivity
它们是通过这种方式关联的.
They are related this way.
活动
has_many:activity_object_activities,:dependent =>:destroy
has_many:activity_objects,:through =>:activity_object_activities
has_many :activity_object_activities,:dependent => :destroy
has_many :activity_objects, :through => :activity_object_activities
破坏后:do_something_on_activity_object_related
after_destroy :do_something_on_activity_object_related
ActivityObject
has_many:activity_object_activities,:depend =>:destroy
has_many:activities,:through =>:activity_object_activities
has_many :activity_object_activities, :dependent => :destroy
has_many :activities, :through => :activity_object_activities
ActivityObjectActivity
属于:activity,:depend =>:destroy
纯属_to:activity_object
belongs_to :activity, :dependent => :destroy
belongs_to :activity_object
当我对某项活动进行销毁时,发现 activity_object_activities
表项在 do_something_on_activity_object_related
调用之前由于 dependent:destroy 而被删除.代码>.因此,因此,在销毁活动时调用
do_something_on_activity_object_related
方法时,将无法找出与活动相关的 activity_object
.
When I do a destroy on an activity, I observe the activity_object_activities
table entry is getting deleted before the call of do_something_on_activity_object_related
due to dependent: destroy
.
So because of this, when the do_something_on_activity_object_related
method is called when the activity is destroyed, it is not able to find out the activity_object
associated with the activity.
有没有一种方法,可以在破坏与活动相关的关联之前调用此 do_something_on_activity_object_related
.有什么方法可以更改 after_destroy
回调的顺序.
Is there a method by which I can call this do_something_on_activity_object_related
before the associations related with the activity are destroyed.
Is there any way I can change the order of the after_destroy
callbacks.
谢谢.
推荐答案
您可以自己负责删除/销毁依赖性,并确保在您完成 do_something_on_activity_object_related
You could take responsibly for the delete/destroy dependencies yourself and make sure they get triggered after you have finished your do_something_on_activity_object_related
所以不是
has_many :activity_object_activities,:dependent => :destroy
has_many :activity_objects, :through => :activity_object_activities
after_destroy :do_something_on_activity_object_related
执行以下操作:
has_many :activity_object_activities
has_many :activity_objects, :through => :activity_object_activities
after_destroy do
do_something_on_activity_object_related
ActivityObjectActivity.destroy_all(activity_id: self.id)
end
从联接表中删除项目时,可以使用 delete_all
而不是 destroy_all
来解决.但是您在示例中使用了destroy,而我在这里也使用了它.
When removing items from the join table you should be fine by using delete_all
instead of destroy_all
. But you used destroy in your example to I used it here too.
这篇关于Rails中的after_destroy回调顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!