Question

I am trying to write an active record validation that allows any string but does not allow nil.

The problem with validates_presences_of is that it returns false for "" or " " which I want to consider valid.

I have also tried to do validates_length_of :foo, :minimum => 0 which did not work

I have also tried t o do validates_length_of :foo, :minimum => 0, :unless => :nil? which also did not work. Both of these allowed for nil values to be set and the validation still returns true.

Am i missing something here? I feel like it shouldnt be this hard to simply validate that the element is not nil.

Was it helpful?

Solution

validate :blank_but_not_nil

def blank_but_not_nil
   if self.foo.nil?
     errors.add :foo, 'cannot be nil'
   end
end

OTHER TIPS

Can you try:

validates_length_of :foo, :minimum => 0, :allow_nil => false

For example:

User < ActiveRecord::Base
  validates_length_of :name, :minimum => 0, :allow_nil => false
end

> u=User.new
> u.valid?  #=> false  #u.name is nil
> u.name=""
> u.valid?  #=> true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top