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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With