【问题标题】:Rails - AciveRecord use :dependent => :destroy on conditionRails - ActiveRecord 使用 :dependent => :destroy on condition
【发布时间】:2011-08-28 08:00:18
【问题描述】:

根据条件销毁对象的所有依赖项的最佳/DRY 方法是什么。 ?

例如:

class Worker < ActiveRecord::Base
 has_many :jobs , :dependent => :destroy
 has_many :coworkers , :dependent => :destroy
 has_many :company_credit_cards, :dependent => :destroy
end 

条件是 关于销毁:

if self.is_fired? 
 #Destroy dependants records
else
 # Do not Destroy records
end 

有没有办法在 :dependent 条件下使用 Proc。 我找到了单独销毁依赖项的方法,但这对于进一步的关联来说并不干燥且灵活,

注意:我已经编造了这个例子..不是一个实际的逻辑

【问题讨论】:

    标签: ruby-on-rails ruby activerecord destroy


    【解决方案1】:

    没有。您应该删除 :dependent =&gt; :destroy 并添加 after_destroy 回调,您可以在其中编写任何您想要的逻辑。

    class Worker < ActiveRecord::Base
      has_many :jobs
      has_many :coworkers
      has_many :company_credit_cards
      after_destroy :cleanup
    
      private
      def cleanup
        if self.is_fired?
          self.jobs.destroy_all
          self.coworkers.destroy_all
          self.company_credit_cards.destroy_all
        end
      end
    end 
    

    【讨论】:

    • 请小心回调,因为它们可以正常工作,除非您正在处理大量数据,而这些回调会给您带来很大的性能问题。解决方案可能是“批量删除”,rails 不支持关联,因此您需要编写一些代码
    • .is_fired 是什么?方法呢?我似乎在其他任何地方都找不到它。
    猜你喜欢
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    相关资源
    最近更新 更多