ActiveRecord Validations Basics
Fast recall
Quick revision
Core answer
validates :name, presence: true add errors when the rule fails; valid? runs the checks, errors explains them, save returns false, and save! raises ActiveRecord::RecordInvalid. Validations improve feedback and domain consistency, but critical guarantees such as uniqueness, foreign keys, and non-null values also need database constraints because concurrent or bypassing writes can avoid model checks.Whether you know validates with presence/uniqueness/numericality, that they run before save (return false on fail), and errors land on record.errors.
Validating in the controller instead of the model (duplicated, easy to miss), or not checking save's return.
validates :field, presence/uniqueness/numericality run before save; save/create return false and errors land on record.errors if they fail.
Interview-ready guide
Interview answer
Active Record validations express rules that model values should satisfy before a normal create or update writes to the database. Built-in validators cover presence, length, numericality, format, inclusion, uniqueness, and associations. Custom validation methods can express a clear rule involving several attributes.
Calling valid?, save, create, or update runs the relevant checks. A failure adds structured entries to errors and prevents that INSERT or UPDATE. save returns false, while save! raises ActiveRecord::RecordInvalid; both leave the rejected values available for a form or API error response.
A uniqueness validation performs a query and improves feedback, but two concurrent requests can both pass before either commits. A unique database index decides that race. NOT NULL, check constraints, and foreign keys likewise protect data written through bulk SQL, maintenance scripts, or code paths that skip validations.
Use conditions or validation contexts only for real lifecycle differences; too many contexts make validity depend on a hidden call path. Bulk methods such as update_all intentionally skip model validations and callbacks. Critical rules therefore belong in the database as well as in the model's learner-friendly feedback.
An HTML form can render errors.full_messages, while an API can return structured field errors, often with status 422. If a database uniqueness constraint wins a race, translate that known conflict safely too. The two layers complement each other: clear feedback before the write and guaranteed integrity at commit.
ActiveRecord Validations Basics
Direct Answer
Active Record validations check a model's application-level rules before normal create or update operations write to the database. Declarations such as validates :name, presence: true add errors when the rule fails; valid? runs the checks, errors explains them, save returns false, and save! raises ActiveRecord::RecordInvalid. Validations improve feedback and domain consistency, but critical guarantees such as uniqueness, foreign keys, and non-null values also need database constraints because concurrent or bypassing writes can avoid model checks.
Deep Dive & Architecture
A validation run starts with a model's current in-memory attributes. Each applicable rule can add one or more errors keyed by attribute or by the model as a whole. valid? returns a boolean but does not persist; save combines validation with the write only when no errors remain.
Conditional and contextual validations change when rules apply. They are useful for genuine lifecycle differences, but too many contexts can make the model valid in one path and invalid in another without an obvious reason. A stable invariant should normally apply on every write.
The uniqueness validator performs a query; it is not a lock. Concurrent transactions may observe no matching value and then both try to insert. A unique index lets the database arbitrate the race, while the application catches and translates the resulting constraint error where appropriate.
Some APIs intentionally skip the model lifecycle for bulk operations or maintenance. Their names and documentation should make that bypass visible, and the database must still protect the rules that can never be relaxed. Tests should cover both the helpful model message and the actual database constraint.
Code Example
class Account < ApplicationRecord
validates :email, presence: true, uniqueness: true
end
class AddUniqueIndexToAccounts < ActiveRecord::Migration[8.1]
def change
add_index :accounts, :email, unique: true
end
end
account = Account.new(email: "")
unless account.save
puts account.errors.full_messages.join(", ")
end
Common Mistakes & Pitfalls
Validating in the controller instead of the model (duplicated, easy to miss), or not checking save's return.
Check your understanding
Answer these without looking back at the article.
- What is the difference between `save` and `save!` after validation fails?
- Why is `validates :email, uniqueness: true` insufficient by itself?
- Which Active Record write methods can bypass validations?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.