0
0
RailsHow-ToBeginner · 3 min read

How to Use find Method in Rails ActiveRecord

In Rails, use Model.find(id) to fetch a record by its primary key (usually ID). It raises an error if no record is found, so use find_by(id: id) for a safe alternative that returns nil instead.
📐

Syntax

The find method is called on an ActiveRecord model to retrieve a record by its ID. You pass one or more IDs as arguments.

  • Model.find(id): Finds a single record by ID.
  • Model.find([id1, id2, ...]): Finds multiple records by IDs.

If the record(s) do not exist, find raises an ActiveRecord::RecordNotFound error.

ruby
User.find(1)
User.find([1, 2, 3])
💻

Example

This example shows how to use find to get a user by ID and handle the case when the user is not found.

ruby
begin
  user = User.find(1)
  puts "User found: #{user.name}"
rescue ActiveRecord::RecordNotFound
  puts "User not found"
end
Output
User found: Alice
⚠️

Common Pitfalls

Using find without handling exceptions can crash your app if the record is missing. Also, find only works with IDs, not other attributes.

For safer queries, use find_by which returns nil if no record matches.

ruby
user = User.find_by(id: 999)
if user
  puts "User found: #{user.name}"
else
  puts "User not found"
end
Output
User not found
📊

Quick Reference

MethodDescriptionReturnsRaises Error?
find(id)Finds record by IDRecordYes, if not found
find([id1, id2, ...])Finds multiple records by IDsArray of recordsYes, if any not found
find_by(attribute: value)Finds first record matching attributeRecord or nilNo

Key Takeaways

Use Model.find(id) to get a record by its ID but handle exceptions for missing records.
find raises an error if the record is not found; use find_by for a safe nil return.
find only works with primary keys; use other query methods for different attributes.
Always rescue ActiveRecord::RecordNotFound when using find to avoid app crashes.