All Articles

Normalizing Attributes in Rails 7.1 using ActiveRecord::Base::normalizes

Rails 7.1 adds ActiveRecord::Base::normalizes API. The normalizes API is applied on model attributes by applying some set of rules, such as converting all email addresses to lowercase, removing leading/trailing whitespace, or enforcing a specific format before they are saved to the database.

Normalization of data helps to organize it in a structured and consistent way, making it easier to query, update, and maintain. It also reduces data redundancy and minimizes the risk of errors and inconsistencies.

Before Rails 7.1, you could normalize attributes using normalize gem or using before_save model callbacks.

class User < ApplicationRecord
  normalizes :email,  with: -> email { email.strip.downcase }
  normalizes :phone,  with: -> phone {  Phonelib.parse(phone).to_s }
  normalizes :avatar, with: -> avatar { avatar.present? ? URI.parse(avatar) : "https://placeholder-avatar-url.com" },
                      apply_to_nil: true
end

user = User.create(email: "ABHAY@EXAMPLE.COM")
user.email    # => abhay@example.com

user = User.create(phone: "+91-8390333333")
user.phone    # => +918390333333

user = User.create(phone: "+91-83903-33333")
user.phone    # => +918390333333

Normalizes Defaults

  • Normalization is by default applied to the finder method.
  • It is not typically applied to nil values. To normalize nil value, you can enable flag apply_to_nil.
  • Also, existing values in the database are not normalized until a new value is assigned.
# Normalize finder method
user = User.find_by(email: "ABHAY@EXAMPLE.COM")
user.email    # => abhay@example.com

# Normalize with apply_to_nil
user = User.create(avatar: nil)
user.avatar   # => "https://placeholder-avatar-url.com"

Happy Coding!!