Validating that at least one attribute in a list is present: validates_presence_of_any

Posted by Tim Connor Tue, 20 Nov 2007 05:10:00 GMT

Make a lib/custom_validations.rb file, with these contents

module CustomValidations
  def validates_presence_of_any(*attrs)
    options = attrs.last.is_a?(Hash) ? attrs.pop.symbolize_keys : {}
    attrs   = attrs.flatten
    send(validation_method(options[:on] || :save)) do |record|
      return if options[:if] && !evaluate_condition(options[:if], record)
      attr_list = attrs.map{|a| a.to_s.humanize}.to_sentence(:connector => "or", :skip_last_comma => true)
      record.errors.add :base, "Either #{attr_list} needed." if attrs.all?{ |attr| record.send(attr).blank?}
    end
  end
end
and then “extend CustomValidation” in your model. Then you can

 validates_presence_of_any :first_attr, :second_attr, :third_attr

Thanks to bitsweat on #caboose for help with a succinct name that follows the convention.

Comment form

(leave url/email »)

Help with Textile (code)