Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How do I validate to allow blanks ("") but not nil (NULL in database)

In an ActiveRecord (or ActiveModel) I would like the following spec to pass

it { should allow_value("").for(:my_string) }
it { should_not allow_value(nil).for(:my_string) }

I have tried

validates :my_string, {
  :length => { :in => 0..255 },
  :presence => true,
  :allow_blank => true,
  :allow_nil => false,
}

and also

validates :my_string, {
  :length => { :in => 0..255 },
  :allow_blank => true,
  :allow_nil => false,
}

But either it allows both "" and nil or none of them.

like image 737
Jarl Avatar asked Sep 12 '12 20:09

Jarl


3 Answers

This works for me

  validates :my_string, length: { in: 0..255, allow_nil: false }

If you just want to validate that the field is not null, but don't care about blank/empty strings, this works:

  validates :my_string, length: { minimum: 0, allow_nil: false, message: "can't be nil" }
like image 144
Chris Bloom Avatar answered Oct 22 '22 13:10

Chris Bloom


You can try doing:

validates :my_string, exclusion: { in: [nil]}

It is part of the validations themselves in ActiveRecord.

I've tried the others and all of them are very compliated or allow nil too.

like image 30
Sergio Ocón-Cárdenas Avatar answered Oct 22 '22 13:10

Sergio Ocón-Cárdenas


You might need to do a custom validation for this:

validates :my_string, :length => { :in => 0..255 }
validate :my_string_is_valid

def my_string_is_valid
  self.errors.add :base, 'My string can not be nil' if self.my_string.nil? 
end
like image 31
weexpectedTHIS Avatar answered Oct 22 '22 12:10

weexpectedTHIS