我有一个模型,根据其当前状态需要不同的验证器。我应该如何为每个实例调用 ActiveRecord 验证器?我想尽可能多地重复使用管道,但我不确定如何继续。
class Order < ActiveRecord::Base
attr_accessible :state
validate :state_specific_validations
def state_specific_validations
if :paid == self.state
# Warning: here be Unicorns...
# Wishful thinking...
validate_presence_of :paid_at
validate_associated :purchaser
# Hopeful. What are the validators called internally in Rails?
errors << PresenceValidator.new(self, :paid_at).valid?
errors << AssociationValidator.new(self, :paid_at).valid?
# Plan B
# ... Hoping for help from the audience ...
else
# Even more complicated validator logic, hoping for some DRY validators
end
end
end
我可以只使用自定义验证器,但为什么我需要复制所有内置验证器逻辑(i18n 错误消息等)?
有没有一种简洁的方法可以将 Rails 验证器作为实例方法调用?我认为 Sequel 的基于实例的验证器的方法比 ActiveRecord 的基于类的方法更合理,但我不在这里判断。我只是想回到解决更有趣的问题。我只是希望其他人已经遇到过这个问题,并且可以为我指出一些有趣的要点或宝石。