Search code examples
ruby-on-railsvalidation

Rails 3 Validation :presence => false


Here's what I expected to be a perfectly straightforward question, but I can't find a definitive answer in the Guides or elsewhere.

I have two attributes on an ActiveRecord. I want exactly one to be present and the other to be nil or a blank string.

How do I do the equivalent of :presence => false? I want to make sure the value is nil.

validates :first_attribute, :presence => true, :if => "second_attribute.blank?"
validates :second_attribute, :presence => true, :if => "first_attribute.blank?"
# The two lines below fail because 'false' is an invalid option
validates :first_attribute, :presence => false, :if => "!second_attribute.blank?"
validates :second_attribute, :presence => false, :if => "!first_attribute.blank?"

Or perhaps there's a more elegant way to do this...

I'm running Rails 3.0.9


Solution

  • class NoPresenceValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)                                   
        record.errors[attribute] << (options[:message] || 'must be blank') unless record.send(attribute).blank?
      end                                                                           
    end    
    
    validates :first_attribute, :presence => true, :if => "second_attribute.blank?"
    validates :second_attribute, :presence => true, :if => "first_attribute.blank?"
    
    validates :first_attribute, :no_presence => true, :if => "!second_attribute.blank?"
    validates :second_attribute, :no_presence => true, :if => "!first_attribute.blank?"