Ruby on Rails - Scopes in Rails
Introduction
Scopes in Rails are a way to encapsulate common queries into reusable methods. They help to keep your code DRY (Don't Repeat Yourself) and make your queries more readable and maintainable. This guide will cover how to create and use scopes in Rails models.
Key Points:
- Scopes are methods that encapsulate common queries.
- Scopes can be chained together for more complex queries.
- This guide covers how to define and use scopes in Rails models.
Defining Scopes
Scopes are defined in the model using the scope
method. Here is a simple example:
# app/models/article.rb
class Article < ApplicationRecord
scope :published, -> { where(published: true) }
end
In this example, the published
scope returns all articles where the published
attribute is true
.
Using Scopes
Once defined, you can use scopes in your queries just like any other method. Here is an example:
# Fetch all published articles
published_articles = Article.published
Chaining Scopes
Scopes can be chained together to create more complex queries. Here is an example:
# app/models/article.rb
class Article < ApplicationRecord
scope :published, -> { where(published: true) }
scope :recent, -> { order(created_at: :desc) }
end
# Fetch all published articles, ordered by most recent
recent_published_articles = Article.published.recent
Scopes with Parameters
Scopes can also accept parameters to make them more flexible. Here is an example:
# app/models/article.rb
class Article < ApplicationRecord
scope :by_author, ->(author_id) { where(author_id: author_id) }
end
# Fetch all articles by a specific author
author_articles = Article.by_author(1)
Combining Scopes with Class Methods
While scopes are great for simple queries, more complex logic can be encapsulated in class methods. Here is an example:
# app/models/article.rb
class Article < ApplicationRecord
scope :published, -> { where(published: true) }
def self.recent_published
published.order(created_at: :desc)
end
end
# Fetch all published articles, ordered by most recent
recent_published_articles = Article.recent_published
Default Scopes
Default scopes are used to apply a scope to all queries for a model. Use them with caution as they can have unexpected side effects. Here is an example:
# app/models/article.rb
class Article < ApplicationRecord
default_scope { where(active: true) }
end
# Fetch all active articles
active_articles = Article.all
In this example, the default_scope
ensures that only articles with active: true
are returned by default.
Conclusion
Scopes in Rails are a powerful way to encapsulate common queries and make your code more readable and maintainable. By using scopes, you can keep your code DRY and create flexible, reusable query methods for your models.