0
0
RailsHow-ToBeginner · 3 min read

How to Use Scope in Rails Model in Ruby on Rails

In Ruby on Rails, you use scope in a model to define reusable query methods that return an ActiveRecord::Relation. You declare a scope with a name and a lambda containing the query logic, making your code cleaner and easier to maintain.
📐

Syntax

A scope is defined inside a Rails model using the scope method. It takes two parts:

  • Name: The name you call to run the query.
  • Lambda: A block that returns an ActiveRecord query.

This creates a method you can chain with other queries.

ruby
scope :scope_name, -> { where(condition) }
💻

Example

This example shows a Post model with scopes to get published posts and recent posts.

ruby
class Post < ApplicationRecord
  scope :published, -> { where(published: true) }
  scope :recent, -> { order(created_at: :desc).limit(5) }
end

# Usage in Rails console or controller
Post.published.recent
Output
# Returns the 5 most recent posts where published is true
⚠️

Common Pitfalls

Common mistakes when using scopes include:

  • Defining scopes without a lambda, which runs the query once at load time instead of when called.
  • Using scopes that return arrays instead of ActiveRecord::Relation, which breaks chaining.
  • Writing complex logic inside scopes instead of using methods or concerns.

Always use a lambda to ensure the query runs fresh each time.

ruby
class Post < ApplicationRecord
  # Wrong: runs once when class loads
  scope :published, -> { where(published: true) }

  # Right: runs query fresh each time
  scope :published, -> { where(published: true) }
end
📊

Quick Reference

Scope UsageDescription
scope :active, -> { where(active: true) }Defines a scope named 'active' to filter active records
Model.activeCalls the 'active' scope to get filtered records
Model.active.recentChains scopes to combine filters and ordering
scope :by_name, ->(name) { where(name: name) }Scope with parameter to filter by name

Key Takeaways

Use scope with a lambda to define reusable query methods in Rails models.
Scopes return ActiveRecord::Relation, allowing chaining of queries.
Always use lambdas to ensure queries run fresh each time the scope is called.
Avoid putting complex logic inside scopes; keep them simple and focused on queries.
Scopes improve code readability and maintainability by encapsulating common queries.