What are Rails scopes?

Answer

ActiveRecord scopes are named, reusable query fragments defined in a model using the scope macro. Example: scope :published, -> { where(published: true) } and scope :recent, -> { order(created_at: :desc).limit(10) }. Scopes return an ActiveRecord relation, so they can be chained: Post.published.recent. Scopes with parameters: scope :by_author, ->(author) { where(author: author) }. Scopes make query intent explicit and DRY. They are equivalent to defining class methods but with the added guarantee of returning a relation even when the condition is falsy.