ruby 15 lines · 6 steps

Normalizing user input in Rails models

How a Rails model cleans up attributes before validating them.

Explained by highlit
1class User < ApplicationRecord
2 has_secure_password
3 
4 normalizes :email, with: ->(email) { email.strip.downcase }
5 normalizes :phone, with: ->(phone) { phone.gsub(/\D/, "") }
6 normalizes :username, with: ->(username) { username.strip.gsub(/\s+/, "_").downcase }
7 normalizes :website, with: ->(url) { url.blank? ? url : url.sub(%r{\Ahttps?://}i, "") }
8 
9 validates :email, presence: true, uniqueness: true,
10 format: { with: URI::MailTo::EMAIL_REGEXP }
11 validates :phone, length: { is: 10 }, allow_blank: true
12 validates :username, presence: true, uniqueness: true,
13 length: { in: 3..30 },
14 format: { with: /\A[a-z0-9_]+\z/ }
15end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Normalizing attributes before validation means your rules check clean data, not raw input.
  2. 2Pairing normalization with a matching validation prevents subtle mismatches like case-sensitive uniqueness bugs.
  3. 3Declarative model macros keep data-cleaning logic centralized instead of scattered across controllers.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Normalizing user input in Rails models — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code