在Rails中,如何确定一个纪录是由相关的破坏:破坏的回调? [英] In rails, How to determine if a record was destroyed by a dependent: :destroy callback?

查看:105
本文介绍了在Rails中,如何确定一个纪录是由相关的破坏:破坏的回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个记录我与 after_destroy 挂钩,需要做的是了解为何一条记录被破坏的Rails应用程序。更具体地说,如果记录被级联被破坏,因为它的家长说相关:摧毁,它需要做的事情比如果记录被单独摧毁不同

我试图做的是看它的母公司是破坏,才弄清楚,相关:?:摧毁回调完成之前父被破坏。这是有道理的,因为它应该能够失败。 (即限制)。

那么,如何做到这一点?

解决方案

要做到这一点的方法之一是使用 before_destroy 回调中的父对象,以纪念所有子对象的通过家长摧毁破坏。就像他的:

 类YourClass
  before_destroy:mark_children

  ...
  ...

  高清mark_children
    [:association1,:association2]。每做|协会| #阵列应该inclue协会名称恨:依赖=> :摧毁选项
      self.send(协会)。每个做|孩子|
        母公司为已删除#号子对象
      结束
    结束
  结束
结束
 

您还可以使用ActiveRecord的思考,以确定哪些全自动协会都​​被标记为:依赖=> :摧毁。这样做是有帮助的,当你需要在许多类此功能。

I've got a record in my Rails app with an after_destroy hook that needs to do be aware why the record gets destroyed. More specifically, if the record is being destroyed in a cascade because its parent says dependent: :destroy, it needs to do things differently than if the record was individually destroyed.

What I tried to do is to see if its parent was destroyed?, only to figure out that dependent: :destroy callbacks are done before the parent is destroyed. Which makes sense because it should be able to fail. (i.e. restrict).

So, how do I do this?

解决方案

One way to do this is using the before_destroy callback in the parent object to mark all child objects as destroyed through parent destroy. Like his:

class YourClass
  before_destroy :mark_children

  ...
  ...

  def mark_children
    [:association1, :association2].each do |association|   # Array should inclue association names that hate :dependent => :destroy option
      self.send(association).each do |child|
        # mark child object as deleted by parent
      end
    end
  end
end

You can also use ActiveRecord Reflections to determine automaticly which associations are marked as :dependent => :destroy. Doing this is helpfull when you need this function in many classes.

这篇关于在Rails中,如何确定一个纪录是由相关的破坏:破坏的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆