Rails 7.1 introduced a new method called ActiveRecord::Base::normalizes
which can be used to declare normalizations for attribute values. This can be especially useful for sanitizing user input, ensuring consistent formatting, or cleaning up data from external sources.
To use the normalizes
method, you first need to define a normalization for the attribute you want to normalize. This can be done by calling the normalizes
method on your model class, passing in the name of the attribute and the name of the method that you want to use to apply the normalization.
1
2
3
class User < ActiveRecord::Base
normalizes :email, with: -> email { email.downcase }
end
1
2
user = User.create(email: "joHnNy.ApPleSeEd@AppLe.com")
user.email # => johnny.appleseed@apple.com
The normalizes
method can be used to define normalizations for a variety of attributes, including dates, numbers, and strings.
1
2
3
class User < ActiveRecord::Base
normalizes :name, with: -> name { name.titleize }
end
1
2
user = User.create(name: "johnny appleseed")
user.name # => "Johnny Appleseed"
The normalizes
method is a powerful way to ensure the integrity of your data. It can help you to avoid errors caused by invalid user input or inconsistent data.