Junior Track Roadmap

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
Free preview · Lesson 1 3 min read

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 lessons
Type to start searching...