0
0
RailsHow-ToBeginner · 3 min read

How to Find a Record in Rails: Simple Guide with Examples

In Rails, you can find a record using Model.find(id) to get a record by its ID, or Model.find_by(attribute: value) to find the first record matching a condition. For multiple records, use Model.where(attribute: value) which returns a collection.
📐

Syntax

Here are the main ways to find records in Rails:

  • Model.find(id): Finds a record by its unique ID. Raises an error if not found.
  • Model.find_by(attribute: value): Finds the first record matching the condition or returns nil if none found.
  • Model.where(attribute: value): Returns all records matching the condition as a collection (can be empty).
ruby
User.find(1)
User.find_by(email: 'user@example.com')
User.where(active: true)
💻

Example

This example shows how to find a user by ID, by email, and all active users.

ruby
class User < ApplicationRecord
end

# Find user by ID
user = User.find(1)
puts user.name

# Find user by email
user_by_email = User.find_by(email: 'user@example.com')
puts user_by_email&.name || 'No user found'

# Find all active users
active_users = User.where(active: true)
active_users.each { |u| puts u.name }
Output
John Doe Jane Smith Alice Johnson Bob Lee
⚠️

Common Pitfalls

Common mistakes when finding records in Rails include:

  • Using find with an ID that does not exist, which raises ActiveRecord::RecordNotFound and can crash your app if not handled.
  • Expecting find_by or where to raise errors when no records are found; they return nil or empty collections instead.
  • Using where when you want a single record, which returns a collection and may cause confusion.

Correct usage example:

ruby
# Wrong: This raises error if no user with ID 999
User.find(999)

# Right: Handle error with rescue
begin
  user = User.find(999)
rescue ActiveRecord::RecordNotFound
  puts 'User not found'
end

# Right: Use find_by to get nil if not found
user = User.find_by(id: 999)
puts user ? user.name : 'User not found'
Output
User not found User not found
📊

Quick Reference

MethodDescriptionReturnsRaises Error if Not Found?
find(id)Finds record by IDSingle recordYes
find_by(attribute: value)Finds first record matching conditionSingle record or nilNo
where(attribute: value)Finds all records matching conditionCollection (can be empty)No

Key Takeaways

Use Model.find(id) to get a record by ID but handle exceptions for missing records.
Use Model.find_by to safely find the first record matching a condition without errors.
Use Model.where to get all records matching a condition as a collection.
Remember find raises error if record not found; find_by and where do not.
Choose the method based on whether you expect one or many records.