Ruby on rails 3 在销毁之前对共享模型进行干燥验证

Ruby on rails 3 在销毁之前对共享模型进行干燥验证,ruby-on-rails-3,validation,callback,dry,Ruby On Rails 3,Validation,Callback,Dry,为了防止删除相关记录,我在每个模型上应用before_destroy回调方法 我在一个模块中定义了几个相关的记录验证方法,以便在销毁回调之前将它们共享给不同的模型: class Teacher < ActiveRecord::Base include RelatedModels before_destroy :has_courses ... end class Level < ActiveRecord::Base include RelatedModels be

为了防止删除相关记录,我在每个模型上应用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
班主任
这些在Rails4中被贬低了(您必须使用),但似乎仍然是Rails3核心的一部分


观察员类

“侦听”模型中的指定操作,并提供扩展功能。正如他们的文档所述,它们特别适合于消除模型的混乱,允许您将许多功能组合到一组中心功能中

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

class-RelatedObserverclass 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