Skip to the workspace
Pebellslearn by building
Models  ›  Lesson

Validations

Validations 12 minValidations declare what valid data looks like; save and create return false and fill errors when a record is invalid, while the bang versions raise instead.

ruby on rails / Validations

Explore each scene at your own pace.

01 · The rule

The rule

Validations

A member submits a review with no rating and a body of "ok". Should it be saved? Validations are the model's answer. They live in one place, so every controller, console session and background job that saves a review obeys the same rules.

The rule

Declare the rules on the model; save says yes or no, errors say why.

class Review < ApplicationRecord
  belongs_to :book
  belongs_to :member

  validates :rating, numericality: { only_integer: true, in: 1..5 }
  validates :body, presence: true, length: { minimum: 10 }
  validates :member_id, uniqueness: { scope: :book_id,
                                      message: "has already reviewed this book" }
end

Common built-in validators:

  • presence: true — not nil or blank
  • length: { minimum:, maximum:, in: }
  • numericality: — a number, with options like greater_than: or only_integer:
  • inclusion: { in: [...] } — one of a fixed set
  • format: { with: /regex/ }
  • uniqueness: — no other row has this value (optionally within a scope:)

What happens when rules fail:

review = Review.new(rating: 7, body: "ok")
review.valid?                 # => false
review.save                   # => false, nothing written
review.errors.full_messages   # => ["Book must exist", "Member must exist",
                              #     "Rating must be in 1..5",
                              #     "Body is too short (minimum is 10 characters)"]
review.save!                  # raises ActiveRecord::RecordInvalid

save, create and update return true or false (create returns the object; check persisted?). Their bang twins save!, create!, update! raise instead. Use the plain ones in controllers, where a failure is expected and shown to the user, and the bang ones in scripts and seeds, where a failure should be loud.

A few methods skip validations entirely: update_column, update_columns, update_all, insert_all and save(validate: false). Use them only when you mean it.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.