How to Use find_by in Rails: Simple Guide with Examples
In Rails, use
find_by to get the first record matching given attributes. It returns the record or nil if none found, unlike find which raises an error.Syntax
The find_by method takes one or more attribute-value pairs as arguments and returns the first record matching those attributes.
Example: Model.find_by(attribute: value)
If no record matches, it returns nil instead of raising an error.
ruby
User.find_by(email: 'user@example.com')Example
This example shows how to find a user by email using find_by. It returns the user object if found or nil if not.
ruby
class User < ApplicationRecord end # Assume a user exists with email 'alice@example.com' user = User.find_by(email: 'alice@example.com') if user puts "Found user: #{user.email}" else puts "User not found" end # Searching for a non-existing email user2 = User.find_by(email: 'bob@example.com') puts user2.nil? ? 'User not found' : 'User found'
Output
Found user: alice@example.com
User not found
Common Pitfalls
- Using
find_bywhen you expect a record to always exist can causenilerrors if not checked. - Unlike
find,find_bydoes not raise an exception if no record is found. - Passing multiple attributes returns the first record matching all conditions (AND logic).
- Do not confuse
find_bywithwhere(...).first—find_byis more concise and readable.
ruby
wrong_user = User.find_by(email: 'missing@example.com') # If you try to call a method on wrong_user without checking, it raises NoMethodError # Correct way: user = User.find_by(email: 'missing@example.com') if user puts user.name else puts 'User not found' end
Quick Reference
| Usage | Description |
|---|---|
| Model.find_by(attribute: value) | Returns first record matching attribute or nil |
| Model.find_by(attr1: val1, attr2: val2) | Returns first record matching all attributes (AND) |
| Returns nil if no match | Does not raise error like find |
| Use with care to check for nil | Avoid NoMethodError by checking result |
Key Takeaways
Use find_by to get the first record matching given attributes or nil if none found.
Always check if the result is nil before calling methods on it to avoid errors.
find_by accepts multiple attributes and matches all (AND condition).
It is more concise and readable than where(...).first for simple queries.
Unlike find, find_by does not raise an exception if no record exists.