Search code examples
ruby-on-railsrubyrails-activerecordactivesupport

ActiveRecord validation for nil


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.


Solution

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