在Rails中after_destroy回调顺序

时间:2012-01-24 09:12:08

标签: ruby-on-rails-3.1 callback

我使用PostgreSql作为数据库,使用Rails 3.1.3和ruby 1.9.3 我有3个型号。

  • Activity
  • ActivityObject
  • ActivityObjectActivity

他们是这样的。

活动

  

has_many:activity_object_activities,:dependent => :破坏
  has_many:activity_objects,:through => :activity_object_activities

     

after_destroy:do_something_on_activity_object_related

ActivityObject

  

has_many:activity_object_activities,:dependent => :破坏
  has_many:activities,:through => :activity_object_activities

ActivityObjectActivity

  

belongs_to:activity,:dependent => :破坏
  belongs_to:activity_object

当我对某个活动进行销毁时,我发现activity_object_activities表条目因do_something_on_activity_object_related而被调用dependent: destroy之前被删除了。 因此,当活动被销毁时调用do_something_on_activity_object_related方法时,它无法找到与活动相关联的activity_object

是否有一种方法可以在与活动相关的关联被销毁之前调用此do_something_on_activity_object_related。 有什么办法可以改变after_destroy回调的顺序。

提前致谢。

1 个答案:

答案 0 :(得分:5)

您可以自行负责删除/销毁依赖项,并确保在完成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即可。但你在你的例子中使用了破坏,我也在这里使用它。