Introduction
Scopes help you write reusable and clear database queries in Rails models. They keep your code clean and easy to understand.
Scopes help you write reusable and clear database queries in Rails models. They keep your code clean and easy to understand.
scope :scope_name, -> { where(condition) }active column is true.scope :active, -> { where(active: true) }scope :recent, -> { order(created_at: :desc).limit(5) }scope :by_category, ->(category) { where(category: category) }This example defines three scopes in the Product model. You can call them to get products that are available, expensive, or belong to a specific brand.
class Product < ApplicationRecord scope :available, -> { where(available: true) } scope :expensive, -> { where('price > ?', 100) } scope :by_brand, ->(brand) { where(brand: brand) } end # Usage examples: Product.available Product.expensive Product.by_brand('Nike')
Scopes return an ActiveRecord::Relation, so you can chain them like Product.available.expensive.
Always use lambdas (-> { }) to define scopes to avoid unexpected query execution.
Scopes make queries reusable and easy to read.
Define scopes inside models using scope :name, -> { ... }.
Scopes can take parameters to customize queries.
scopes in a Rails model?active that selects records with status: 'active'?scope :name, -> { query }.scope :published, -> { where(published: true) }
scope :recent, -> { order(created_at: :desc) }Article.published.recent.to_sql return?published adds a WHERE clause, recent adds ORDER BY.scope :recent, { order(created_at: :desc) }recent_active that returns records which are both active: true and created in the last 7 days. Which is the correct way to define this scope?where calls to combine multiple conditions logically ANDed.7.days.ago to compare dates properly.Pass the test and this pattern moves unknown