skip to content

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%

answer

  1. applies to every query, even associations
  2. also sets attributes on new and create
  3. default order appends to later order calls
  4. unscoped drops everything, foreign key included
  5. all_queries: true for record update and delete

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.

solid answer

~40 s

`default_scope { where(status: "published") }` makes `Article.all`, `find`, counts and `author.articles` all filter on `status`, and it also sets `status` to `"published"` on `Article.new`. That invisibility is the risk: an admin page cannot see drafts, a default `order` stays in front of every later `order` call, and the escape hatch is blunt. `Article.unscoped` drops every condition, and `author.articles.unscoped` returns every article in the table because the author condition goes too. Narrower tools exist: `unscope(where: :status)` or `unscope(:order)` remove one part, and `Article.unscoped { author.articles.to_a }` lifts the default scope while keeping the association. By default the scope is not applied to a record's own update, delete or reload; `all_queries: true` adds its where clauses there as well.

code

ruby · 7 lines
ruby
class Article < ApplicationRecord
  default_scope { where(status: "published") }
end

author.articles.unscoped.count                 # every article in the table
author.articles.unscope(where: :status).count  # this author's articles, any status
Article.unscoped { author.articles.to_a }      # same idea, block form

go deeper

for a junior

Recall that default_scope applies to every query of the model and that unscoped removes it.

for a middle

Explain how default_scope sets attributes on new records, why a default order appends, and how unscoped differs from unscope(where: ...).

for a senior

Show that you audit code inheriting a default_scope, replace bare unscoped calls on associations, and reserve all_queries: true for tenant-style columns where writes must stay constrained.

for a principal

Weigh implicit global filters against explicit scopes for multi-tenant data, considering the cost of a forgotten condition versus the cost of surprising queries.

## What default_scope does `default_scope` registers a scope that Active Record applies to **every query built from the model**, unless something removes it. In a travel magazine where only published articles should normally be visible: ```ruby class Article < ApplicationRecord default_scope { where(status: "published") } end Article.all # ... WHERE "articles"."status" = 'published' Article.find(42) # draft 42 raises ActiveRecord::RecordNotFound author.articles # ... WHERE status = 'published' AND author_id = 7 Article.new.status # => "published" ``` Several `default_scope` declarations, including ones inherited from a parent class or a concern, are combined with `AND`, and so is any later `where`, even on the same column. The body must be a block or another callable; passing a relation directly raises `ArgumentError`. ## Why teams avoid it 1. **It is invisible at the call site.** `Article.where(author_id: 7)` reads like "all of this author's articles" but is not. Editors' dashboards, exports and background jobs that need drafts must remember to escape it. 2. **It leaks into writes.** Hash-style equality conditions become attribute defaults: `Article.new` and `Article.create` get `status: "published"`, so a "new draft" form starts out published unless the code overrides it. 3. **A default order sticks.** With `default_scope { order(published_at: :desc) }`, a later `Article.order(:title)` **appends**, producing `ORDER BY published_at DESC, title ASC`. Removing it needs `reorder` or `unscope(:order)`. 4. **The main escape hatch is too wide.** `unscoped` removes everything, not just the default scope (below). ## unscoped versus unscope | Call | What it removes | |---|---| | `Article.unscoped` | every scope: the default scope **and** anything chained before it | | `author.articles.unscoped` | everything, including the `author_id` condition: all articles in the table | | `Article.unscoped { author.articles.to_a }` | the default scope inside the block; the association keeps its foreign key | | `relation.unscope(where: :status)` | only `where` conditions on `status` | | `relation.unscope(:order)` | only the `ORDER BY` | `unscoped` is delegated from a relation straight to the model, which is why it forgets the association's own condition. `unscope` accepts the names of query parts (`:where`, `:order`, `:select`, `:group`, `:limit`, `:joins` and more) and, for `where`, a hash naming the column. It also **persists across `merge`**, so it can be used inside an association definition: `has_many :all_articles, -> { unscope(where: :status) }, class_name: "Article"`. ## all_queries: record-level writes and reload Without options, the default scope applies to queries that **select** rows and to records being **built or created**. It does not constrain operations on a single loaded record: - `article.update(title: "...")` updates `WHERE id = 42` only. - `article.destroy` deletes `WHERE id = 42` only. Declaring `default_scope -> { where(magazine_id: Current.magazine_id) }, all_queries: true` adds the scope's **where clauses** (not its order) to those record-level updates, deletes and reloads as well. That is mostly used for tenant or shard columns, where an `UPDATE` that ignores the tenant condition would be a data-isolation bug. ## Removing a default_scope from an existing app Deleting the line is easy; finding everything that relied on it is the work: 1. Add an explicit named scope with the same condition, such as `scope :published, -> { where(status: "published") }`. 2. Search for every query on the model and its associations, and add `.published` where public pages need it. 3. Check record-building paths: forms and factories that relied on `Article.new` presetting `status` now need an explicit value or a database default. 4. Remove the `default_scope` and the `unscoped` calls that existed only to escape it. 5. Watch logs and error reports for pages that suddenly show drafts. ## Safer alternatives - Use an **explicit named scope** (`Article.published`) on public pages and plain `Article` in admin code. The intent is visible where it matters. - Keep `default_scope` for genuinely universal rules, such as a tenant column with `all_queries: true`, where forgetting it would be worse than its surprises. - When you inherit a `default_scope`, prefer `unscope(where: :column)` or the block form of `unscoped` over the bare `unscoped` call.

  • With `default_scope { order(published_at: :desc) }`, why does `Article.order(:title)` not sort by title first?
    `order` appends to the existing order values, and the default scope's order is already there, so the SQL is `ORDER BY published_at DESC, title ASC`. Use `reorder(:title)` to replace the ordering, or `unscope(:order).order(:title)`.
  • Does `default_scope` apply to `Article.where(status: "draft").update_all(...)`?
    Yes. `update_all` runs on a relation, and relations built from the model start from the default scope, so the `WHERE` combines `status = 'published'` with `status = 'draft'` and matches nothing. `all_queries:` concerns single-record update, delete and reload, not relation-level `update_all`.

  • unscoped on an association removes only the default scope and keeps the owner condition
  • default_scope affects reads only; Article.new is untouched
  • a later order call replaces the order from default_scope
  • all_queries: true also applies the default scope's order to record updates
  • unscope(:where) removes only the conditions that came from default_scope