In an Active Record model, how does a lambda scope differ from a class method returning a relation, especially when the condition is nil?
answer
- both are chainable class methods
- the body must be callable
- what a falsy scope body yields
- a class method returns its body as is
- lambda arguments are checked strictly
basics
~20 sA scope is a class method generated from a lambda: if the lambda returns nil or false, the scope returns all instead, so chains keep working, while a hand-written class method returns exactly what its body returns, nil included.
solid answer
~40 s`scope :featured, -> { where(featured: true) }` defines `Article.featured`, also callable on any relation or association such as `author.articles.featured`. A class method `def self.featured = where(featured: true)` behaves the same in the normal case, because Active Record delegates class methods to relations too. The difference shows when a condition is optional: `scope :in_country, ->(code) { where(country_code: code) if code.present? }` returns `all` when `code` is blank, so `Article.published.in_country(params[:country]).featured` still works, while the same body in a class method returns `nil` and the next call raises `NoMethodError`. The scope body must be callable; passing a bare relation raises `ArgumentError`, which is what stops a timestamp from being frozen at class load. Class methods remain the better home for multi-step logic.
code
ruby · 10 linesclass Article < ApplicationRecord
scope :in_country, ->(code) { where(country_code: code) if code.present? }
def self.by_author(id)
where(author_id: id) if id
end
end
Article.published.in_country(nil).featured # => relation, chain continues
Article.published.by_author(nil).featured # NoMethodError: by_author returned nilgo deeper
Recall the scope syntax with a lambda and an argument, and that scopes chain from the model, a relation or an association.
Explain why a nil-returning scope yields all while a class method yields nil, and why scope bodies must be callable rather than relations.
Show that you choose class methods for multi-step logic yet make every branch return a relation, so search code that chains optional filters never meets nil.
Discuss where query logic should live as models grow: scopes, query objects or concerns, weighing discoverability against bloated model classes.
## What a scope is A **named scope** in Active Record is declared with the `scope` macro: a name plus a callable body, almost always a lambda, that returns a relation. ```ruby class Article < ApplicationRecord scope :published, -> { where(status: "published") } scope :featured, -> { where(featured: true) } scope :recent, ->(days = 30) { where(published_at: days.days.ago..) } scope :in_country, ->(code) { where(country_code: code) if code.present? } end Article.published.featured.recent(7) author.articles.published # works on associations too ``` Under the hood `scope` defines a **singleton method** on the model and registers it so relations of that model respond to it as well. The documentation itself calls it syntactic sugar for a class method. Two differences make it more than sugar. ## Difference 1: nil and false become `all` When the lambda returns `nil` or `false`, the generated method returns the current relation instead. That makes optional filters safe to chain: | Definition | `in_country(nil)` returns | `.featured` afterwards | |---|---|---| | `scope :in_country, ->(code) { where(...) if code.present? }` | the relation unchanged (all articles in the chain) | works | | `def self.in_country(code); where(...) if code.present?; end` | `nil` | `NoMethodError` | A search page for a travel magazine that chains `in_country(params[:country])`, `by_author(params[:author_id])` and `recent(params[:days])` depends on this. With class methods, each one needs an explicit fallback such as `code.present? ? where(country_code: code) : all`. ## Difference 2: the body must be callable `scope` raises `ArgumentError` ("The scope body needs to be callable.") when given a relation instead of a lambda. That rule exists because a relation built in the class body is evaluated **once, at class load**: - `where(published_at: 1.week.ago..)` written directly would freeze "one week ago" at boot. - Inside a lambda, `1.week.ago` is evaluated on every call. Lambdas are also strict about arguments, so `Article.recent(7, 3)` raises `ArgumentError`, and a default such as `(days = 30)` is evaluated per call. ## Arguments A scope's lambda takes arguments like any lambda, including defaults and keyword arguments: ```ruby scope :recent, ->(days = 30) { where(published_at: days.days.ago..) } scope :by_region, ->(region:, featured: false) { where(region: region, featured: featured) } Article.recent # last 30 days, computed now Article.recent(7) # last 7 days Article.by_region(region: "alps") ``` The default `30` and the `days.days.ago` call are evaluated on each call, so a long-running process never reuses a stale date. A missing required keyword raises `ArgumentError` at the call site, which is clearer than a query that silently ignores a `nil`. ## What stays the same 1. **Chaining.** Both a scope and a class method that returns a relation can be chained from the model, from another relation and from an association. Active Record generates relation methods that run the class method inside the relation's scoping, so `Article.published.titles` sees the `published` condition. 2. **Building records.** Conditions from both apply to `new` and `create` on the chain: `Article.published.new.status` is `"published"`. 3. **Laziness.** Neither runs SQL until the relation is loaded. ## Where each fits - **Scope**: a one-line, composable filter or ordering, especially one with an optional argument. - **Class method**: several steps, early returns, branching on types, or calls to other services. Make it end with a relation (`all`, `none` or a `where`) on every branch so it chains like a scope. - **Extensions**: a scope can take a block of extra methods available only on that scope's result, the same mechanism `extending` exposes on any relation. ## Pitfalls interviewers probe - Naming a scope after an existing Active Record class method or relation method raises `ArgumentError` when the class loads. - A scope that returns a single record (`first`) or an Array is no longer chainable; use a class method and name it as a finder instead. - Scope order matters for `order` but not for `where`: `where` conditions combine with `AND` whatever their order.
- How do you rewrite the class method so it chains as safely as the scope?Return a relation on every branch: `def self.by_author(id) = id ? where(author_id: id) : all`. `all` inside a class method called on a relation returns that relation, so earlier conditions such as `published` are kept.
- What does a block passed to `scope` do?It defines extension methods available only on relations produced by that scope, for example `scope :featured, -> { where(featured: true) } do def headline = first end`. Active Record builds a module from the block and applies it with `extending`, the same mechanism `Article.all.extending(SomeModule)` uses.
- a scope runs its query immediately and returns an Array
- scope :recent, where(published_at: 1.week.ago..) works and stays fresh
- a class method returning nil is turned into all, exactly like a scope
- class methods cannot be called on a relation or an association, only scopes can
- the order of where-based scopes in a chain changes which rows match