21

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.

6 Answers 6

39

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" }
0
13

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.

1
  • It stopped working after I upgraded to rails 6.1
    – mikdiet
    Apr 12, 2022 at 23:33
7

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
1
  • 2
    This is what I have done... However I find it strange that Rails does not support this situation.
    – Jarl
    Sep 25, 2012 at 9:19
3

You can create a simple custom validator (placed in app/validators dir)

class NotNilValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors[attribute] << "must not be nil" if value.nil?
  end
end

and then

validates :my_string, not_nil: true
2
  • This can also be written as record.errors.add(attribute, 'must not be nil) if value.nil? May 28, 2015 at 9:57
  • Wilson's answer is missing the closing quote. It should be record.errors.add(attribute, 'must not be nil') if value.nil? Jan 9, 2020 at 13:38
1

Or maybe:

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

Seems that allow_nil does not override allow_blank. So you better no specify allow_blank

2
  • trying out your suggestion, makes it { should_not allow_value(nil).for(:my_string) } fail.
    – Jarl
    Sep 18, 2012 at 14:15
  • 3
    when you have presence: true, allow_blank: true, allow_nil: false at the same time. It will allow nil
    – Ivan Wang
    Aug 24, 2015 at 13:31
1

This works for me:

validates_exclusion_of :my_string, in: [nil]
1
  • Welcome to Stack Overflow. Could you please add a few words to help explain your answer?
    – Joey
    May 6, 2019 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.