after_destroy callback order in Rails

孤街浪徒 提交于 2020-12-30 13:13:59

问题


I am using PostgreSql as database and Rails 3.1.3 and ruby 1.9.3 I have 3 models.

  • Activity
  • ActivityObject
  • ActivityObjectActivity

They are related this way.

Activity

has_many :activity_object_activities,:dependent => :destroy
has_many :activity_objects, :through => :activity_object_activities

after_destroy :do_something_on_activity_object_related

ActivityObject

has_many :activity_object_activities, :dependent => :destroy
has_many :activities, :through => :activity_object_activities

ActivityObjectActivity

belongs_to :activity, :dependent => :destroy
belongs_to :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.

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.

Thanks In Advance.


回答1:


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

So instead of

has_many :activity_object_activities,:dependent => :destroy
has_many :activity_objects, :through => :activity_object_activities

after_destroy :do_something_on_activity_object_related

do this:

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

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.



来源:https://stackoverflow.com/questions/8984284/after-destroy-callback-order-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!