Queries & Scopes in Ruby

From the Ruby on Rails cheat sheet · Models & Active Record · verified Jul 2026

Queries & Scopes

Query database with Active Record

ruby
# Find records
Post.find(1)
Post.find_by(title: 'Hello')
Post.where(published: true)
Post.all

# Chain queries
Post.where(published: true).order(created_at: :desc).limit(10)
✅ Use find_by instead of where().first
💡 includes() prevents N+1 query problems
🔍 Scopes make queries reusable and chainable
⚡ Use select() to fetch only needed columns
modelsqueriesactive-recordscopes

More Ruby tasks

Back to the full Ruby on Rails cheat sheet