如何调用ActiveRecord的验证器的实例方法(ALA续集)? [英] How to call ActiveRecord validators as instance methods (ala Sequel)?

查看:110
本文介绍了如何调用ActiveRecord的验证器的实例方法(ALA续集)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,需要不同的验证程序取决于其当前状态。我应该如何去了解每个实例调用ActiveRecord的验证?我想重新使用尽可能多的水管是可能的,但我不知道如何继续。

I've got a model that needs different validators depending on its current state. How should I go about calling ActiveRecord validators per instance? I'd like to reuse as much plumbing as possible, but I'm not sure how to continue.

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

我可以使用自定义的验证,但为什么我需要复制所有内置的验证逻辑(国际化的错误信息,等等。)?

I could just use custom validators, but why would I need to duplicate all the built-in validator logic (i18n error messages, etc.)?

有没有一种简洁的方式调用Rails的验证作为实例方法呢? 我认为基于实例验证续集的做法比的ActiveRecord的阶级为基础的较为合理的,但我不是在这里来判断。我只是想拿回解决更有趣的问题。我只是希望其他人遇到这一点,并能指出我一些有趣的依据或宝石。

Is there a neat way of calling the Rails validators as instance methods? I think Sequel's approach of instance-based validators is more reasonable than ActiveRecord's class-based, but I'm not here to judge. I'd just like to get back to solving more interesting problems. I'm just hoping that others have come across this and can point me to some interesting gist or gem.

推荐答案

我肯定是pretty的所有的验证_ * 方法可以采取:如果选项 - 它可以指向另一个方法(可能接受一个Proc以及),这样你就可以打破你的验证更是这样的:

I'm pretty sure all of the validate_* methods can take an :if option - which can point to another method (and likely accept a Proc as well), so you could break up your validations to be more something like:

validates_presence_of :paid_at, :if => :paid?
validates_association :purchaser, :if => :paid?

要进一步清理东西,还有的with_options助手:

To clean things up further, there's the with_options helper:

with_options :if => :paid? do |v|
  v.validates_presence_of :paid_at
  v.validates_association :purchaser
end

不知道或者可以使用标准使用验证:custom_validate_method 虽然 - 但它不会让我感到吃惊。

Not sure if either can be used with a standard validate :custom_validate_method though - but it wouldn't surprise me.

这篇关于如何调用ActiveRecord的验证器的实例方法(ALA续集)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆