ActiveRecord: unscope/reorder
This course covers default_scope in ActiveRecord and the tools for working around it. It shows how a default_scope adds its condition to every query on a model, including find(id), which raises RecordNotFound for rows that exist. It explains unscope for removing one named condition or clause, unscoped in bare and block forms for removing all default scoping, and reorder for replacing an ORDER BY. It also shows how simple equality scopes set attribute values on new records, and why this app uses an explicit scope :active instead.
What you'll learn
- ✓How default_scope applies one condition to every query on a model
- ✓Why find(id) raises RecordNotFound for a real row under a default_scope
- ✓How unscope removes one where condition or a whole order or limit clause
- ✓How unscoped removes all default scoping, in bare and block forms
- ✓How reorder replaces the ORDER BY while chained order calls stack columns
- ✓How simple equality conditions in default_scope become attribute values on new records
default_scope: every query, one line, no exceptions
Every ActiveRecord querying course so far filtered explicitly, with .where(status: 0) or Catalog::Course.active: one call, applied when a query chose to apply it. default_scope is a different kind of tool. It's a condition declared once, in the model, and folded into every query against that model…
Read the full lesson free →Curriculum
7 lessonsdefault_scope: every query, one line, no exceptions
How default_scope adds one condition to every query on a model, and why Catalog::Course uses an explicit scope instead.
The find(id) trap
default_scope also filters find(id), which raises RecordNotFound for a real row that fails the scope's condition.
unscope: removing one condition, precisely
Using unscope to drop one named where condition, or whole order and limit clauses, while keeping the rest.
unscoped: the blunt instrument, bare and block forms
The bare and block forms of unscoped, which remove all default scoping at once, compared with unscope.
reorder vs order: replacing, not appending
Chained order calls stack their columns, while reorder replaces the whole ORDER BY built so far.
Scope conditions becoming attribute defaults
A simple equality condition in default_scope becomes the attribute value on new records; complex conditions do not.
Putting it together: scoping that doesn't surprise anyone
Each tool applied to one hypothetical model with default_scope, and why this app's explicit scope is a deliberate choice.