If you only want to run a validation on an attribute if it is valid at that 
point in the validation process then here's a trick:

module AttributeValidation
  extend ActiveSupport::Concern

  included do
    attribute_method_suffix '_valid?', '_invalid?'
  end

  private

  def attribute_valid?(attr)
    !attribute_invalid?(attr)
  end

  def attribute_invalid?(attr)
    errors.include?(attr.to_sym)
  end
end

include this module in AR::Base or specific models - it's up to you. Once 
included you can then set up your validations like this:

class User < ActiveRecord::Base
  include AttributeValidation

  attr_accessible :name, :age

  validates :name, presence: true, length: { maximum: 100 }
  validates :age, presence: true, numericality: { only_integer: true }
  validate :over_minimum_age, if: :age_valid?

  def over_minimum_age
    errors.add(:age, :invalid) if age < 16
  end
end

this will only run the minimum age validation once it has passed the presence 
and numericality checks. One advantage of doing this is you don't need guard 
checks when comparing the age (normally you'd get a "NoMethodError: undefined 
method `<' for nil:NilClass")


Andrew

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.

Reply via email to