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

Rails 7.1 introduced a powerful new API for normalizing attributes: ActiveRecord::Base::normalizes. This feature makes it easy to ensure consistent data formatting across your application.

What is Attribute Normalization?

Attribute normalization is the process of transforming data into a consistent format before it's saved to the database. This ensures data consistency and can prevent issues with duplicate records or inconsistent formatting.

The New API

Rails 7.1 provides a clean, declarative way to normalize attributes:

class User < ApplicationRecord
  normalizes :email, with: ->(email) { email.strip.downcase }
  normalizes :phone, with: ->(phone) { phone.gsub(/\D/, '') }
end

Common Use Cases

Email Normalization

class User < ApplicationRecord
  normalizes :email, with: ->(email) { email.strip.downcase }
end

This ensures that emails are always stored in lowercase, preventing duplicate accounts with different cases.

Phone Number Normalization

class Contact < ApplicationRecord
  normalizes :phone, with: ->(phone) { phone.gsub(/\D/, '') }
end

This removes all non-digit characters from phone numbers, ensuring consistent storage.

Whitespace Normalization

class Post < ApplicationRecord
  normalizes :title, with: ->(title) { title.strip }
end

This removes leading and trailing whitespace from titles.

Multiple Normalizations

You can apply multiple normalizations to a single attribute:

class User < ApplicationRecord
  normalizes :email, with: ->(email) { email.strip.downcase }
  normalizes :name, with: ->(name) { name.strip.titleize }
end

Benefits

The normalizes API provides several benefits:

  • Declarative: Clear and easy to understand
  • Automatic: Applied before validation and saving
  • Consistent: Ensures data integrity across your application
  • DRY: Centralizes normalization logic

Conclusion

The normalizes API in Rails 7.1 is a welcome addition that simplifies attribute normalization and helps maintain data consistency in your applications.

Normalizing Attributes in Rails 7.1 using ActiveRecord::Base::normalizes - Abhay Nikam