Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 371
LikeMaBell Avatar asked Apr 09 '12 08:04

LikeMaBell


2 Answers

For allowing an object to be valid if and only if a specific attribute is nil, you can use "inclusion" rather than creating your own method.

validates :name, inclusion: { in: [nil] }

This is for Rails 3. The Rails 4 solution is much more elegant:

validates :name, absence: true
like image 120
La-comadreja Avatar answered Nov 13 '22 23:11

La-comadreja


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?"
like image 21
Kris Avatar answered Nov 13 '22 21:11

Kris