1

为了防止删除相关记录,我在每个模型上应用 before_destroy 回调方法

我在一个模块中定义了几个相关记录验证方法,以便可以将它们共享给不同模型的 before_destroy 回调:

class Teacher < ActiveRecord::Base
  include RelatedModels
  before_destroy :has_courses
  ...
end

class Level < ActiveRecord::Base
  include RelatedModels
  before_destroy :has_courses
  ...
end

module RelatedModels

  def has_courses
    if self.courses.any?
      self.errors[:base] << "You cannot delete this while associated courses exists"
      return false
    end
  end

  def has_reports
    if self.reports.any?
      self.errors[:base] << "You cannot delete this while associated reports exists"
      return false
    end
  end

  def has_students
    if self.students.any?
      self.errors[:base] << "You cannot delete this while associated students exists"
      return false
    end
  end

  ...

end

但它看起来不是很干燥

知道如何用一种方法做到这一点吗?元编程不是我的技能

提前致谢

4

1 回答 1

0

您可能想尝试一个observer class

这些在 Rails 4 中被贬值了(你必须使用rails-observersgem),但似乎仍然是 Rails 3 核心的一部分


观察者类

“监听”模型中的指定动作,并提供扩展功能。正如他们的文档所述,它们特别适合整理模型,使您可以将许多功能组合到一组中央功能中

以下是您可能想做的事情(请记住,我只在 Rails 4 中使用过这些):

class RelatedObserver < ActiveRecord::Observer
  observe :teachers, :school

  def before_destroy(record)
      associations = %w(teachers schools reports)
      associations.each do |association|
          if record.send(association).any?
              self.errors[:base] << "You cannot delete this while associated #{association.pluralize} exists"
              return false
          end
      end
  end
end

这是一个很好的资源给你

于 2013-11-02T19:25:10.783 回答