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 returnsnilif 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
findwith an ID that does not exist, which raisesActiveRecord::RecordNotFoundand can crash your app if not handled. - Expecting
find_byorwhereto raise errors when no records are found; they returnnilor empty collections instead. - Using
wherewhen 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
| Method | Description | Returns | Raises Error if Not Found? |
|---|---|---|---|
| find(id) | Finds record by ID | Single record | Yes |
| find_by(attribute: value) | Finds first record matching condition | Single record or nil | No |
| where(attribute: value) | Finds all records matching condition | Collection (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.