How to call ActiveRecord validators as instance methods (ala Sequel)?

邮差的信 提交于 2019-12-06 03:52:11

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?

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

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

Is there any reason why this is inappropriate? It seems like it might work, but maybe metaprogramming warped my brain...

class Order < ActiveRecord::Base
  attr_accessible :state

  validate :state_specific_validations

  def state_specific_validations
    if :paid == self.state
      class << self
        validate_presence_of :paid_at
        validate_associated :purchaser
      end
    end
  end
end

Worst part is that tests are passing, so I'm not sure if I solved it or I need better tests. For example, I'm not 100% positive this singleton modification does not affect other Orders.

sigh Need some sleep.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!