High Leverage Rails
Introduction
Introduction to this course
Why use Ruby on Rails
Why use SQLite
Ruby on Rails + SQLite
Powering Your App with SQLite
Creating tables
Timestamps
Column types
Typeof
Ruby types
Creating table introduction
Creating table advanced
Inserting data
Updating data
Upserting data
Reading data
Virtual columns
Enums
Introduction to JSON
Indexing JSON
JSON table functions
Building a Modern Rails Application
Creating a new Rails application
Installing Solid Queue
Installing Solid Cache
Installing Solid Cable
Dockerfile
Application overview
Authentication
Base styles
Registration
Scaffolding posts
Polishing posts
Scaffolding comments
Polishing comments
Polishing models
Polishing controllers
Creating new post
Updating post
Reviewing MVP
Tagging posts
Custom tags
Friendly URLs
Full text search
Deploying & Operating Your App
Backups
Check Litestream locally
Verifying backups
Deployment options
Deploying with Hatchbox
Deployment constraints
Vertical scaling
Database access
Migrations
Locked video

Please purchase the course to watch this video.

Video thumbnail
Powering Your App with SQLite
Reading data

Full Course

$
129
$179
USD, one-time fee
This course came at the perfect time. I’ve recently gotten back into Rails after an 18-year hiatus, and this was a perfect refresher and shows just how much you can accomplish with Rails right out of the box.
Garrett Winder
Garrett Winder

Move fast and fix things

Application monitoring that helps developers get it done.

Rails hosting made simple

Deploy apps to servers that you own and control.

Summary

Learn how to query data efficiently in Rails using Active Record methods like where, find, and find_by. Discover how to sort results with order and leverage raw SQL for advanced queries. Master best practices for database retrieval and filtering with insights from the Active Record guide.

Links

Active Record Guide

Video Transcript

Now that we know how to create and update data in our tables, let’s do a quick introduction to querying data using Active Record.

Jumping back into our playground, we have our posts table with title and body columns, our Post model, and two records already inserted. Now, let’s explore some core query methods that are essential for working with Active Record.

Of course, there are many more methods, and you can find a link to the Active Record guide in the documentation below, which breaks down all public methods available for reading from the database. For now, we’ll focus on a handful of key queries.

Using where to Build Conditional Queries

The most important query method to know is where, which allows us to build conditional SELECT queries.

For example, if we search for posts where the title is "Title 1":

Post.where(title: "title one")

Active Record generates the following SQL query:

SELECT * FROM posts WHERE title = ?

Here’s what’s happening:

  • Active Record generates a generic SQL query that is not hardcoded to a particular value.
  • The query can be reused multiple times with different values, improving performance and security (preventing SQL injection).
  • The result is an array of Post instances that match the condition.

If we pass an array of values, Active Record uses the IN operator instead of =:

Post.where(title: ["title one", "other title"])

This generates:

SELECT * FROM posts WHERE title IN (?, ?)

This acts like an OR condition, returning all records that match either of the values.

Finding a Single Record with find and find_by

If we want to retrieve a single record instead of an array of results, we have two options:

  1. find (for retrieving by ID)
ruby
Post.find(1)

This directly queries by primary key (id) and returns one record. If no record is found, it raises an error.

  1. find_by (for retrieving by a unique attribute)
ruby
Post.find_by(title: "title one")

This is useful when you don’t know the id but have a unique field. Unlike find, this does not raise an error if no record is found—it simply returns nil.

Sorting Results with order

By default, queries return results in the order they were inserted. If we want to control sorting, we can use order:

Post.where(title: ["title one", "title two"]).order(:title)

This generates:

SELECT * FROM posts WHERE title IN (?, ?) ORDER BY title ASC

To control the sort direction, we can specify ascending (ASC) or descending (DESC):

Post.order(title: :desc)
Post.order(title: :desc, body: :asc)

This ensures that ties in title are resolved using body.

Using Raw SQL with where

Active Record is powerful, but sometimes you need more complex conditions. You can pass raw SQL inside where:

Post.where("created_at > ?", Time.now)

This generates:

SELECT * FROM posts WHERE created_at > ?

Active Record safely binds the value to prevent SQL injection.

If we change the condition to find older posts:

Post.where("created_at < ?", Time.now)

This returns all records created before the current time.

Recap: Key Query Methods in Active Record

Method Returns Best Use Case
where Array of records Filtering by one or more conditions
find Single record (or error) Fetching a record by ID
find_by Single record (or nil) Finding by a unique attribute
order Array of records Sorting results

There are many additional methods in Active Record for complex queries, grouping, and conditions. If you’re interested in learning more, check out the Active Record guide linked below.

In the next video, we’ll explore more advanced querying techniques, including aggregations and joins.