skip to content

Named Scopes & Laziness

A scope is a named lambda that returns a chainable relation, and nothing reaches the database until the relation loads. Interviewers probe scopes versus class methods and why default_scope surprises.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In Active Record, when does Article.published.featured.order(:published_at) actually query the database, and what do load, loaded? and reset do?

level: juniorimportance: must knowfreq 60%

answer

  1. chaining builds, it does not run
  2. each, to_a or map triggers the SELECT
  3. load returns the relation itself
  4. loaded? caches the records
  5. reset forgets them

basics

~20 s

Building the chain runs no SQL; the SELECT runs when records are first needed, such as on each or to_a. load runs it now and returns the relation, loaded? reports cached records, and reset discards them.

solid answer

~40 s

Every query method (`where`, `order`, a scope) returns a new `ActiveRecord::Relation` describing the query; nothing is sent until code asks for records with `each`, `to_a`, `map`, `records` or similar. That is why a controller can assign `@articles = Article.published.featured.order(:published_at)` and the SELECT only appears in the log while the view iterates. Once loaded, the relation keeps its records, so iterating twice is one query and `loaded?` returns true. `load` forces the query now and returns the relation itself, not an Array. `reset` clears the cached records, and `reload` is `reset` plus `load`. Methods such as `count` or `exists?` do not load; they send their own query.

code

ruby · 8 lines
ruby
articles = Article.published.featured.order(:published_at)  # no query
articles.loaded?        # => false
articles.load           # SELECT ... ; returns the relation
articles.loaded?        # => true
articles.each { }       # no query: cached records
articles.size           # no query
articles.reset          # forget the records
articles.to_a           # SELECT ... again

go deeper

for a junior

Recall that query methods and scopes build a relation lazily and that the SELECT runs when records are iterated.

for a middle

Explain which calls load the relation versus send their own query, and what load, loaded?, reset and reload change.

for a senior

Show that you place loading deliberately, read logs knowing the view triggers queries, and avoid repeated count or exists? calls on relations you are about to load.

for a principal

Discuss how lazy relations shape layering decisions, such as whether controllers hand views relations or loaded data, and how that affects caching and query visibility.

## Relations are query descriptions In Active Record, `Article.published`, `.featured` and `.order(:published_at)` each return an **`ActiveRecord::Relation`**: an object that holds the pieces of a query (conditions, ordering, limits, joins) but no rows. Each call copies the relation and adds one piece, so earlier relations are never modified. ```ruby @articles = Article.published.featured.order(:published_at) # no SQL @articles.to_sql # shows the SELECT without running it @articles.loaded? # => false ``` `Article.all` is a relation too. That design is what makes scopes composable and lets a controller build a query that the view, a partial or a cache block decides whether to run. ## What triggers the query The SELECT runs the first time code needs the **records**: - iteration and conversion: `each`, `map`, `to_a`, `to_ary`, `records` - Array-style methods delegated to the records, such as `length`, `[]`, `sample` - an explicit `load` Other methods send their **own** query without loading the relation: | Call on an unloaded relation | SQL sent | Relation loaded afterwards? | |---|---|---| | `each`, `to_a`, `length` | the full SELECT | yes | | `first` | SELECT ... LIMIT 1 | no | | `count` | SELECT COUNT(*) | no | | `exists?` | SELECT 1 AS one ... LIMIT 1 | no | The Rails console hides laziness: it calls `inspect` on the result of every line, and inspecting an unloaded relation runs a query limited to 11 rows, annotated "loading for inspect". In application code, the query fires where the records are used, typically in the view. ## load, loaded? and the cached records 1. `load` executes the query if the relation is not loaded and returns **the relation itself**, so `Article.published.load` can be assigned and chained like before. Its main uses are forcing the query at a known point (before a long render, or to measure it) and making the records available to several consumers. 2. `loaded?` is `true` once records are cached. After that, `each`, `length`, `size`, `empty?` and `first` answer from memory. 3. Iterating a loaded relation twice does not query twice. Chaining after loading does not reuse the records: `@articles.where(country_code: "PT")` is a **new** relation with an extra condition and runs its own SELECT when used. ## reset and reload - `reset` discards the cached records (and any scheduled background load), so `loaded?` becomes `false` and the next access queries again. - `reload` is `reset` followed by `load`: it re-runs the same query immediately. These matter in long-lived code paths, such as a job that holds a relation while it updates rows and then needs fresh data, or a test that asserts state after a write. ## Building a query in steps Laziness is what makes step-by-step query building cheap. A search action can start from a base relation and add pieces conditionally, and only one SELECT is ever sent: ```ruby articles = Article.published articles = articles.where(country_code: params[:country]) if params[:country].present? articles = articles.featured if params[:featured] == "1" @articles = articles.order(published_at: :desc).limit(20) ``` Each assignment creates a new relation object; none of them queries. The SELECT that reaches the database contains every condition that was added, and it runs once, when the view renders `@articles`. The same property lets a partial receive a relation and decide whether to render it at all. ## Why interviewers ask - To check you can predict **where** a query happens and how many: one SELECT per loaded relation, plus one per `count`, `exists?` or `first` on an unloaded one. - To see whether you understand that a scope returns a relation, not results, so defining scopes is free and loading is the cost. - To probe debugging habits: using `to_sql` to inspect a chain, and noticing that the console runs queries the application might never send.

  • After `articles = Article.featured.load`, does `articles.where(country_code: "PT").to_a` reuse the loaded records?
    No. `where` returns a new relation with an added condition, and that relation is unloaded, so it sends its own SELECT. Filtering already-loaded records in memory would need Ruby's `select` with a block on the records, which is a different trade-off.
  • Why can laziness make a controller look fast in logs and a view look slow?
    The controller only builds the relation, so no SQL is attributed to the action body; the SELECT runs when the template iterates the records. Calling `load` in the controller moves the query to a predictable place without changing what is fetched.

A relation is an order slip at a travel bookshop: you can keep adding lines to it, and nothing leaves the stockroom until someone asks to unpack the parcel. After that the books sit on the counter until you tell the clerk to clear it.

  • each scope in the chain runs its own SELECT as it is called
  • load returns an Array of records
  • count on an unloaded relation loads the records and counts them
  • calling where on a loaded relation filters the cached records in memory
  • the console's behaviour proves the relation queried at assignment time
open as a page

In an Active Record model, how does a lambda scope differ from a class method returning a relation, especially when the condition is nil?

level: middleimportance: must knowfreq 66%

basics

~20 s

A 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.

open as a page

In an Active Record model, why is default_scope considered risky, and how do unscoped, unscope and all_queries: change what it reaches?

level: middleimportance: should knowfreq 52%

basics

~20 s

default_scope silently adds its conditions to every query, association and new record of the model; unscoped removes all scoping including an association's foreign key, unscope removes one named part, and all_queries: true extends the scope's where clauses to record updates and deletes.

open as a page

In Active Record, why return Article.none rather than [] or nil from a method that callers chain onto, and what SQL does it run?

level: middleimportance: should knowfreq 35%

basics

~20 s

Article.none returns a chainable relation that is known to be empty, so callers can keep adding scopes; loading, counting or checking it returns [], 0 or false without sending any SQL, whereas [] and nil break the chain.

open as a page

In a Rails 8.1 controller, what does calling load_async on several relations buy you, and when does it quietly run each query in the foreground instead?

level: seniorimportance: should knowfreq 28%

basics

~20 s

load_async schedules a relation's SELECT on a background thread pool so independent queries overlap; with the default nil executor, inside a transaction, or on an adapter without concurrent connections, it loads immediately in the calling thread.

open as a page