Ruby on rails 如何提高多级依赖销毁性能

Ruby on rails 如何提高多级依赖销毁性能,ruby-on-rails,activerecord,destroy,cascading-deletes,Ruby On Rails,Activerecord,Destroy,Cascading Deletes,在我的项目中,有许多带有关联和依赖::destroy标志的模型。此外,每个模型都与dependent::destroy标志有其他归属的关联。这些模型彼此嵌套,因此当对顶部模型执行destroy时,Rails会在子模型上触发级联destroy 除此之外,模型还有回调,在销毁之前执行 下面是我在上面描述的内容: class Model1Example < ActiveRecord::Base has_many :model2_examples, :dependent => :dest

在我的项目中,有许多带有
关联和
依赖::destroy
标志的模型。此外,每个模型都与
dependent::destroy
标志有其他
归属的关联。这些模型彼此嵌套,因此当对顶部模型执行
destroy
时,Rails会在子模型上触发级联destroy

除此之外,模型还有
回调
,在销毁之前执行

下面是我在上面描述的内容:

class Model1Example < ActiveRecord::Base
  has_many :model2_examples, :dependent => :destroy

  belongs_to :other1_example, :dependent => :destroy
  belongs_to :other2_example, :dependent => :destroy
end

class Model2Example < ActiveRecord::Base
  belongs_to :model1_example
  has_many :model3_examples, :dependent => :destroy

  belongs_to :other3_example, :dependent => :destroy
  belongs_to :other4_example, :dependent => :destroy

  before_destroy :update_something_on_model1
  before_destroy :check_some_inconsistence
end

class Model3Example < ActiveRecord::Base
  belongs_to :model2_example

  belongs_to :other5_example, :dependent => :destroy
  belongs_to :other6_example, :dependent => :destroy

  before_destroy :update_something_on_model2
  before_destroy :check_some_inconsistence
end
class Model1Example:destroy
属于:other1\u示例,:dependent=>:destroy
属于:other2\u示例,:dependent=>:destroy
结束
类Model2Example:destroy
属于:other3\u示例:dependent=>:destroy
属于:other4\u示例,:dependent=>:destroy
销毁前:更新模型1上的内容
销毁前:检查一些不一致之处
结束
类Model3Example:destroy
属于:other6\u示例:dependent=>:destroy
销毁前:更新模型2上的内容
销毁前:检查一些不一致之处
结束
假设在触发
Model1Example
destroy
时,
Model2Example
平均包含约100多个
Model3Example
实例,则会触发许多SQL查询(10k+)因为删除是一条记录一条记录地进行的,而且所有的规则都是针对每个实例执行的……这比用户等待这样一个简单操作所需的时间要多得多

我可以通过使用
上的
dependent::delete\u all
来解决这个性能问题,因为我并不真正关心在触发
Model1Example
destroy
时是否执行所有这些规则

但问题是,当我(从应用程序的其他地方)执行
Model2Example
destroy
时,所有规则都会被执行(特别是
Model3Example
每个实例的规则),前面提到的方法会阻止这一点

对于这种情况,是否有“Rails方法”来实现性能改进?或者我应该使用SQL进行
Model1Example
删除吗


另外,如果我必须使用这种方法,并且我想在销毁
Model1Example
之前检查一些基本内容,那么在哪里进行验证是最好的?控制器?

您是否考虑过将所有这些都放到后台工作人员中?对于这类问题,这个问题有一个很好的答案:谢谢@ThomasR.Koll。事实上,我确实想过,事实上,这是我的第一个想法,但后来我想:当删除完成时,我如何让用户知道?删除标志是一个我没有想到的好主意,但我必须去使用
Model1Example
的每个地方,过滤掉标记为已删除的实例,对吗?想想看,我还应该标记
Model2Example
子实例,因为我可以从其他地方访问它们-让用户在删除这些实例时访问它们是不好的。另外,如果
Model3Example
可以从其他地方访问的实例,我也必须这样做。我个人在我的模型中使用了一个偏执宝石(我是Mongoid btw),所以我在时间戳上有一个删除的_。我相信ActiveRecord和诸如此类的软件都有一个。@ThomasR.Koll您最好在答案中加入您的提示,这样我至少可以对您的想法进行投票;)