我想要一个具有默认验证的超类和可以覆盖默认验证的子类。
class Foo < ActiveRecord::Base
FIELDS = [:field1, :field2]
after_initialize :include_rules
def include_rules
FIELDS.each do |field|
self.class.send(:validates, field, presence: true)
end
end
end
忽略将从超类继承的子类...
每次提交表单时,都会调用 after_initialize 并重复验证。
即提交表格4次
输出:
field1 can't be blank
field1 can't be blank
field1 can't be blank
field1 can't be blank
field2 can't be blank
field2 can't be blank
field2 can't be blank
field2 can't be blank
有什么简单的方法可以只加载一次验证,但在方法中调用它们?