4

I have a migration that creates a string column. I want to allow my column to be nil, but I don't want it to have empty string values (''). Is there anything that I can include in the migration or model to validate that if not nil, then the string is not empty?

1
  • Please, show us what you have already tried. Commented Jan 4, 2019 at 18:07

2 Answers 2

11

What about blank string? (ie: a string like " " with all white spaces?)

I'm not sure if there's something at DB level, but for the activerecord model I would use something like:

validates :my_column, presence: true, allow_nil: true

This validation will check that the string is not empty (it will prevent the model for being saved if the string is " " too, not just "")

https://guides.rubyonrails.org/active_record_validations.html#presence


If you only want to exclude "" but allow " ", then I would use something like

validates :my_column, length: {minimum: 1}, allow_nil: true

Note the difference between using a minimum length (uses length to trigger the validation error) instead of presence (uses the blank? method to trigger the validation error)

https://guides.rubyonrails.org/active_record_validations.html#length (check the tip on the guide about adding a custom message for minimum: 1 since the default error message is plural)

Sign up to request clarification or add additional context in comments.

Comments

0

You could write a custom validator on your model:

validate :validate_not_empty_string

def validate_not_empty_string
  errors.add(:base, "String cannot be empty") if my_column == ""
end

This should not fire for nil, since nil != "".

I would handle this at the model rather than in the migration.

2 Comments

.blank? returns true or false so comparison with "" will not give desired results.
Whoops - I changed plans mid-writing, and forgot to pull out the ".blank?". I've fixed that now.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.