0
0
Ruby on Railsframework~5 mins

Scopes for reusable queries in Ruby on Rails

Choose your learning style9 modes available
Introduction

Scopes help you write reusable and clear database queries in Rails models. They keep your code clean and easy to understand.

When you want to reuse a common database filter in many places.
When you want to give a name to a specific query for better readability.
When you want to chain multiple queries together easily.
When you want to keep your controller or view code simple by moving query logic to the model.
Syntax
Ruby on Rails
scope :scope_name, -> { where(condition) }
Scopes are defined inside Rails model classes.
The lambda (-> { }) delays the query execution until you call the scope.
Examples
This scope finds all records where the active column is true.
Ruby on Rails
scope :active, -> { where(active: true) }
This scope gets the 5 most recent records.
Ruby on Rails
scope :recent, -> { order(created_at: :desc).limit(5) }
This scope accepts a parameter to filter records by a given category.
Ruby on Rails
scope :by_category, ->(category) { where(category: category) }
Sample Program

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.

Ruby on Rails
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')
OutputSuccess
Important Notes

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.

Summary

Scopes make queries reusable and easy to read.

Define scopes inside models using scope :name, -> { ... }.

Scopes can take parameters to customize queries.