Scope là named query được định nghĩa trong model, trả về ActiveRecord::Relation → chainable.
ruby
class Article < ApplicationRecord
scope :published, -> { where(status: "published") }
scope :recent, -> { order(created_at: :desc).limit(10) }
scope :by_tag, ->(tag) { joins(:tags).where(tags: { name: tag }) }
end
Article.published.recent
Article.published.by_tag("ruby")Scope vs class method: scope luôn trả về ActiveRecord::Relation (kể cả khi condition false → trả toàn bộ).
- Class method có thể trả
nil→ chain bị gãy. - Với logic phức tạp hoặc cần trả nil có chủ đích → class method.
A scope is a named query defined on the model that returns an ActiveRecord::Relation and is therefore chainable.
ruby
class Article < ApplicationRecord
scope :published, -> { where(status: "published") }
scope :recent, -> { order(created_at: :desc).limit(10) }
scope :by_tag, ->(tag) { joins(:tags).where(tags: { name: tag }) }
end
Article.published.recent
Article.published.by_tag("ruby")Scope vs class method: a scope always returns an ActiveRecord::Relation (even when the condition is false — it returns all).
- A class method can return
nil, breaking a chain. - Use class methods when logic is complex or when intentionally returning nil is desired.