Jarl
Jarl

Reputation: 2861

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.

Upvotes: 22

Views: 30679

Answers (6)

Tao-Sheng Ou
Tao-Sheng Ou

Reputation: 11

This works for me:

validates_exclusion_of :my_string, in: [nil]

Upvotes: 1

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.

Upvotes: 15

snovity
snovity

Reputation: 1173

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

Upvotes: 3

Chris Bloom
Chris Bloom

Reputation: 3554

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

Upvotes: 40

Lucca Mordente
Lucca Mordente

Reputation: 1131

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

Upvotes: 1

weexpectedTHIS
weexpectedTHIS

Reputation: 3376

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

Upvotes: 7

Related Questions