📅  最后修改于: 2023-12-03 14:46:54.346000             🧑  作者: Mango
Rails scopes allow you to define pre-defined queries for your ActiveRecord models which can be reused across the application. Scopes can save you a lot of time and make your code more concise and readable.
Scopes are defined in the model using the scope
method. The scope
method takes a block where you can define your query using ActiveRecord query methods like where
, order
, etc.
class Article < ApplicationRecord
scope :published, -> { where(published: true) }
end
In the above example, we have defined a scope called published
which returns only the articles that are marked as published
.
Once a scope is defined, it can be used just like a regular ActiveRecord query method. For example, to get all the published articles, you can call the published
scope on the Article
model.
@articles = Article.published
You can also chain multiple scopes to narrow down the results.
@articles = Article.published.order(created_at: :desc)
Dynamic scopes are scopes that take arguments at runtime to customize the query. For example, let's say we want to define a scope that returns articles for a particular category.
class Article < ApplicationRecord
scope :in_category, -> (category) { where(category: category) }
end
We can now use the in_category
scope to get articles for a specific category.
@articles = Article.in_category('Technology')
Scopes are a powerful feature of Rails that can help you write DRY and concise code. By defining common queries as scopes, you can avoid repeating yourself and make your models more expressive.