为了防止删除相关记录,我在每个模型上应用 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
但它看起来不是很干燥
知道如何用一种方法做到这一点吗?元编程不是我的技能
提前致谢