Find Records

This guide shows you how to find records by their primary key or attributes.

Find by ID

user = User.find(1)
if user
  puts "Found: #{user.name}"
else
  puts "Not found"
end

Find by ID (raise if not found)

user = User.find!(1)  # Raises if not found
puts user.name

Find by Attribute

user = User.find_by(email: "john@example.com")
puts user.try(&.name)

Find by Multiple Attributes

Find First Record

Find Last Record

Find All Records

Find with Order

Check if Record Exists

Find or Initialize

Safe Navigation

Use try for safe access:

Verify Find Works

Last updated

Was this helpful?