Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow nil values on string column but not empty string on Rails migration

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?

like image 825
Leticia Esperon Avatar asked Sep 06 '25 03:09

Leticia Esperon


1 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)

like image 88
arieljuod Avatar answered Sep 07 '25 23:09

arieljuod