It happens you need some field in the database to not contain an empty string, but to be NULL. For example, a unique index has been added to this field, meaning there can only be one record with an empty string. However, if the field has a NULL value, it is unique and there can be multiple such records.
If you work with Ruby on Rails, I recommend using the normalizes method added in version 7.1 for this purpose.
You might think the same result could be achieved using the before_validation or before_save callbacks, but this isn’t the case.
Unfortunately, the callbacks won’t be triggered when calling the update_column, update_columns or update_all methods, and therefore the field won’t be normalized.
Don’t be afraid to populate fields with NULL values; otherwise, you’ll fill them with junk data.
class User < ApplicationRecord
normalizes :email, with: ->(email) { email.presence }
# ...
end
user = User.create(email: 'user1@example.com')
user.update(email: '') # now email is nil (or NULL in database)
# it works even in these cases and email will be NULL
user.update_columns(email: '')
User.where(id: user.id).update_all(email: '')
class User < ApplicationRecord
before_validation { self.email = email.presence }
# ...
end
user = User.create(email: 'user2@example.com')
user.update(email: '') # now email is nil (or NULL in database)
# here, callbacks will not be called and the email will be an empty string
user.update_columns(email: '')
User.where(id: user.id).update_all(email: '')