In a Rails 8.1 model, how does normalizes :phone behave on assignment, in where and find_by queries, for nil, and for rows saved earlier?
answer
- applied when assigned, not when read
- hash conditions normalize the query value
- raw SQL strings are left alone
- apply_to_nil: false by default
- normalize_attribute to migrate old rows
basics
~20 snormalizes runs its with: callable whenever the attribute is assigned and on query values in where, find_by and exists? hash conditions, but not in raw SQL strings. nil is skipped unless apply_to_nil: true, and rows saved before the declaration stay raw until reassigned.
solid answer
~40 s`normalizes :phone, with: ->(phone) { phone.gsub(/\D/, "") }` wraps the attribute's type, so the lambda runs on assignment: `Order.new(phone: "(555) 867-5309").phone` is `"5558675309"`, and that is what gets saved. Because hash conditions cast through the same type, `Order.where(phone: "555.867.5309")`, `find_by` and `exists?` normalize the search value too, while a string fragment such as `where("phone = ?", ...)` is passed through untouched. `nil` is skipped by default, which keeps simple lambdas from crashing; `apply_to_nil: true` sends `nil` through as well. Values loaded from the database are not normalized, so rows saved before the declaration stay raw until you call `normalize_attribute(:phone)` and save. `Order.normalize_value_for(:phone, raw)` returns the normalized form without a record. Write the lambda to be idempotent; Rails may apply it more than once.
code
ruby · 13 linesclass Order < ApplicationRecord
normalizes :phone, with: ->(phone) { phone.gsub(/\D/, "") }
normalizes :customer_email, with: ->(email) { email.strip.downcase }
end
order = Order.new(phone: "(555) 867-5309")
order.phone # => "5558675309"
Order.where(phone: "555.867.5309").exists? # cast, so it matches
Order.where("phone = ?", "555.867.5309") # raw SQL, no match
Order.normalize_value_for(:phone, "555 867 5309") # => "5558675309"
# backfill rows saved before the declaration
Order.find_each { |o| o.normalize_attribute(:phone); o.save! }go deeper
Remember that normalizes cleans a value as soon as it is assigned and that nil is skipped unless apply_to_nil: true.
Explain that the rule wraps the attribute type, so hash-condition queries are normalized but raw SQL fragments and loaded values are not.
Plan the backfill for rows saved before the rule, keep normalizers idempotent and pure, and normalize parameters yourself before raw SQL.
Decide which canonical formats the system stores, so every entry point, import and search shares them instead of each cleaning data its own way.
## What normalizes does `normalizes` declares a cleanup rule for one or more attributes: `normalizes :phone, with: ->(phone) { phone.gsub(/\D/, "") }`. It arrived in Rails 7.1 for Active Record, and in Rails 8.1 it is defined in Active Model as `ActiveModel::Attributes::Normalization`, which Active Record includes, so plain Active Model classes can use it as well. Under the hood it decorates the attribute's type: casting a value runs the cast type first and then your callable. Everything that casts a value through that type therefore sees normalized data. ## When the rule runs | Situation | Normalized? | |---|---| | `order.phone = "(555) 867-5309"`, `Order.new(phone: ...)`, `update(phone: ...)` | yes, at assignment | | `Order.where(phone: "555.867.5309")`, `find_by(phone:)`, `exists?(phone:)` | yes, the query value is cast | | `Order.where("phone = ?", "555.867.5309")` | no, raw SQL is passed as written | | a value loaded from the database | no | | a string mutated in place, `order.phone << " "` | yes, re-normalized before validation | | `nil` | no, unless `apply_to_nil: true` | Two consequences: - **Searches agree with storage.** A customer can type the number any way they like in the order-lookup form and `find_by(phone: params[:phone])` still matches. - **Raw SQL is your responsibility.** Normalize the parameter yourself, for example with `Order.normalize_value_for(:phone, params[:phone])`, before putting it into a string fragment. ## nil and apply_to_nil: By default the callable never receives `nil`, so `->(phone) { phone.gsub(/\D/, "") }` is safe for an optional column. Pass `apply_to_nil: true` when the rule should turn `nil` into something, such as `->(note) { note.to_s.strip }` mapping a missing note to an empty string. Then the callable must cope with `nil` itself. ## Rows saved before the declaration Rails deliberately does not normalize values read from the database, to avoid surprising changes when a record is merely loaded. Existing rows therefore keep their old formatting, and a `where(phone:)` lookup with normalized input will not find them. To migrate: 1. load each record in batches, 2. call `order.normalize_attribute(:phone)`, which reassigns the current value through the rule, 3. save it. Until that backfill runs, lookups on legacy rows can miss. ## Writing a good normalizer - Make it **idempotent**: normalizing an already normalized value must not change it, because Rails can apply the rule more than once. - Keep it **pure**: no database calls or external lookups; it runs on every assignment and every query value. - Keep **validation separate**: normalizes shapes the value, and a validation decides whether the shaped value is acceptable, such as a length check on the digits. ## Normalization and validations Because the rule runs at assignment, validations always see the canonical value: - `validates :phone, length: { is: 10 }` checks the digits, not the punctuation the customer typed, - a uniqueness validation compares canonical values, so two formats of one number count as duplicates, - a format validation must describe the canonical form, because the punctuation the customer typed is already gone when it runs. ## Checking it in tests A useful test asserts both directions of the rule: - assigning a formatted value stores the canonical one, - a lookup with a differently formatted value finds the record, - `nil` survives untouched when the column is optional. `Order.normalize_value_for(:phone, "555 867 5309")` is handy in such tests and in service code, because it applies exactly the rule the model declares without building a record. ## Interview angle The question usually starts as "how would you make phone lookups work regardless of formatting?" The strong answer names `normalizes`, explains that hash conditions are normalized while raw SQL is not, and mentions the backfill for rows saved earlier. Older code did the same job with a `before_validation` callback, which cleans values only when the record validates and never touches query values.
- Can a form object that is not backed by a table use normalizes in Rails 8.1?Yes. Since Rails 8.1 the feature lives in `ActiveModel::Attributes::Normalization`. A class that includes `ActiveModel::Attributes` and that module, and declares its attributes with `attribute`, can call `normalizes` exactly as a model does.
- Why is normalizes better than a before_validation callback for cleaning a phone number?A callback runs only when the record validates, so the value is raw between assignment and save and query parameters are never cleaned. `normalizes` hooks the attribute's type, so the value is clean immediately after assignment and the same rule applies to `where` and `find_by` lookups.
- normalizes also rewrites values when records are loaded from the database
- Order.where("phone = ?", raw) is normalized like a hash condition
- The normalizer receives nil unless apply_to_nil: false is passed
- normalizes runs only when save is called, like a before_save callback
- Order.normalize_value_for updates every stored row
Assumes Rails 8.1: normalizes exists since Rails 7.1 and is defined in Active Model since 8.1, so non-database models can include it too.