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?
-
Please, show us what you have already tried.mrzasa– mrzasa2019-01-04 18:07:13 +00:00Commented Jan 4, 2019 at 18:07
2 Answers
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)
Comments
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.