Reputation: 5151
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.
Upvotes: 0
Views: 9282
Reputation: 4877
validate :blank_but_not_nil
def blank_but_not_nil
if self.foo.nil?
errors.add :foo, 'cannot be nil'
end
end
Upvotes: 5
Reputation: 10147
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
Upvotes: 3