0Pricing
Ruby Academy · Lesson

Validations and Queries

Data integrity and querying.

Validations and Queries is a free Ruby Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Ruby Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Validate?

Validations guard your data before it reaches the database. They run when you save a record and reject invalid data with helpful messages.

  • They keep bad data out (missing names, malformed emails).
  • They run in Ruby, so messages are easy to show users.
  • They complement, not replace, database constraints.

Presence Validation

The most common rule is validates :field, presence: true, which requires a non-blank value. Saving without it fails and records an error.

class User < ApplicationRecord
  validates :name, presence: true
end

# User.create(name: "") fails to save

Uniqueness Validation

uniqueness: true prevents duplicate values, such as two users with the same email. Pair it with a unique database index, because the validation alone has a race condition under heavy concurrency.

class User < ApplicationRecord
  validates :email, presence: true, uniqueness: true
end

Format and Length

Other built-in validators:

  • length: { minimum: 8 } for size limits.
  • format: { with: /regex/ } for patterns.
  • numericality: true for numbers.
  • inclusion: { in: [...] } for allowed values.
class User < ApplicationRecord
  validates :password, length: { minimum: 8 }
  validates :age, numericality: { greater_than: 0 }
end

valid? and errors

Call valid? to run validations without saving. After a failed save, record.errors holds the problems, and errors.full_messages gives readable strings for the UI.

user = User.new(name: "")
if user.valid?
  user.save
else
  puts user.errors.full_messages
end

save vs save!

Two save styles:

  • save returns true/false so you branch on the result.
  • save! raises RecordInvalid on failure, useful when invalid data should be an exception.

Same pattern applies to create/create! and update/update!.

user.save   # => false if invalid
user.save!  # => raises if invalid

Custom Validations

For rules beyond the built-ins, write a method and register it with validate. Add problems via errors.add.

class User < ApplicationRecord
  validate :name_not_admin

  def name_not_admin
    if name == "admin"
      errors.add(:name, "cannot be admin")
    end
  end
end

Querying with where

The query interface starts with where, which filters rows. It returns a lazy relation you can chain further before it hits the database.

User.where(active: true)
User.where("age > ?", 18)
User.where(role: ["admin", "editor"])

Ordering and Limiting

Shape results with chainable methods:

  • order(created_at: :desc) sorts.
  • limit(10) and offset(20) paginate.
  • select(:id, :name) picks columns.
User.where(active: true)
    .order(created_at: :desc)
    .limit(10)

Aggregates and Lazy Loading

Aggregate helpers run database functions: count, sum(:amount), average(:age), maximum, minimum. Relations are lazy; the query runs only when you enumerate, call an aggregate, or use to_a.

User.where(active: true).count
Order.sum(:total)
User.average(:age)

Scopes

A scope names a reusable query so you can compose it cleanly. Scopes return relations and chain with each other and with where.

class User < ApplicationRecord
  scope :active, -> { where(active: true) }
  scope :adults, -> { where("age >= ?", 18) }
end

User.active.adults

Quick Check

Test your understanding of validations and queries.

Recap: Validations and Queries

You learned to protect and fetch data:

  • Validations like presence, uniqueness, length, and format guard saves.
  • valid? and errors report problems; save! raises.
  • Custom validations cover special rules.
  • where, order, limit, aggregates, and scopes build lazy queries.

That completes the Models and Active Record course.

Frequently asked questions

Is the “Validations and Queries” lesson free?

Yes — the full text of “Validations and Queries” is free to read here on the web, and the Ruby Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Ruby Academy course, upgrade to CoddyKit PRO.

What will I learn in “Validations and Queries”?

Data integrity and querying. You practise Ruby Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Ruby Academy?

No prior experience is required. Ruby Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Validations and Queries” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Ruby Academy lesson?

Yes. Every Ruby Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Active Record Basics
  2. Migrations
  3. Associations
  4. Validations and Queries
← Back to Ruby Academy