Understanding Rails

Understanding Rails · Season 3: Active Record in depth

Scopes, enums and normalizes

Episode 23 · deep dive · about 4 minutes · Rails 8.1 · by

How was this episode?

The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.

Was it clear?

Not endorsed yet. Are you a Rails developer? What's an endorsement?

Endorse this version To endorse: create an account, confirm your email, then link GitHub.

What changed

  • Version 3, November 21, 2026: A replay on a real app showed version 2's counts were wrong too. The real counts are 501 drafts and 1 published, and the screen now names the notebook it counts.
  • Version 2, November 20, 2026: Changed the published and draft counts, which didn't add up.

Named queries, enum attributes, and cleaning input on the way in.

Free to watch. If it helped, support the series.

Transcript

0:00 Scopes, enums and normalizes

Episode twenty three. Scopes, enums and normalizes. Three short declarations at the top of a model, that give your app its own words. Today: what each one gives you, and the trap in each.

0:16 A scope names a query

A scope names a query. The note model has two already. Recent, ordered newest first. And about, which takes a word, and finds the notes that contain it.

0:27 Scopes chain

Scopes chain, with each other and with any query method. About milk, then recent, then limit three, builds one query: the where, the order, and the limit together. They work through associations too. A notebook's notes, about vet, adds the notebook's id, and the association's own order.

0:46 A scope never returns nil

A scope always returns a relation, even when its body returns nil. In notebook takes a notebook, and adds a where only when one is given. Pass nil, and you get every note, so the chain keeps going.

1:00 A class method can

A class method with the same body doesn't do that. Pass nil, and it returns nil. Chain recent onto it, and you get a no method error: undefined method recent for nil. That's the one real difference. Otherwise, a scope is a class method with a name that reads well.

1:19 default_scope

There's also default scope, and it's best avoided. Give notes a default scope of published notes. Now Note dot count is one. Every query gets the filter, even ones that look unrelated. A new note starts out published. And a notebook's notes only count the published one. You can step around it, but only if you remember it's there.

1:40 enum

Next comes enum. Notes now have a status column: a plain integer, with a default of zero. An enum on status maps names to those numbers. Draft is zero, published is one, and archived is two.

1:55 What enum writes

From that one line, Rails writes a set of methods. Status returns the name, as a string. Draft, with a question mark, asks. Published, with a bang, changes it and saves. And statuses lists the whole map.

2:09 enum scopes

It writes scopes too. Note dot published is a where on status equals one. Not published is the opposite: five hundred and one notes. And you can use the name in a where: status, published.

2:23 Spell out the numbers

In the database, it's still just the number. That's why the hash spells out each number. Write the names as an array instead, and the numbers come from their order. Add a name in the middle later, and you'd quietly change what every saved note means.

2:39 validate true

Assign a status that isn't on the list, and enum raises an argument error: pinned is not a valid status. From a form, that's a crash. Add validate true, and it's a validation error instead: status is not included in the list. The form shows it, like any other error.

2:58 normalizes

Last, normalizes. In episode twenty two, a before validation callback cleaned up tag names, but only when the tag was validated. Normalizes does it the moment the value is assigned. Big Ideas, with spaces around it, is big dash ideas straight away.

3:16 Normalized queries

It works on queries too. Find by name, urgent, in capitals with spaces around it, searches for lowercase urgent, and finds it. And normalize value for shows what any value would become, with no record at all.

3:31 Old data stays messy

Here's the trap. Normalizes cleans values as they're written, not the ones already in the database. We put Someday Maybe into the database with plain SQL. Reading it back gives Someday Maybe, untouched. And find by name, Someday Maybe, finds nothing, because the query is normalized, and the saved value isn't.

3:51 normalize_attribute

Normalize attribute cleans one record, and save writes it back. For a whole table, do the same for each record in a migration or a task. Even update column normalizes, because normalizing is part of how the attribute is written.

4:08 The rules

So: name your queries with scopes, and skip default scope. Give enum explicit numbers, and validate true. And use normalizes for clean data, then fix what's already saved.

4:20 Next

Next: transactions and locking.

Check your understanding

  1. scope :in_notebook, ->(notebook) { where(notebook:) if notebook }. What does Note.in_notebook(nil).recent return?

    • nil
    • A NoMethodError
    • Every note, newest first
    Show answer

    Every note, newest first. A scope always returns a relation. When its body returns nil, you get all, so the chain keeps going. A class method would return nil. Source: Active Record Query Interface: scopes using conditionals (Rails Guides 8.1).

  2. enum :status, [:draft, :published, :archived]. Later someone adds :pinned between :draft and :published. What happens to saved notes?

    • Nothing, Rails stores the names
    • Saved published notes now read as pinned, because the numbers come from the order
    • Rails raises until you write a migration
    • Rails renumbers the saved notes for you
    Show answer

    Saved published notes now read as pinned, because the numbers come from the order. With an array, each name's number is its position. Give enum a hash with explicit numbers so they never move. Source: ActiveRecord::Enum (Rails API 8.1).

  3. Without validate: true, a form sets a note's status to "pinned", which isn't on the list. What happens?

    • An ArgumentError is raised
    • The note is invalid, with status is not included in the list
    • The status is set to nil
    • The note saves with status pinned
    Show answer

    An ArgumentError is raised. enum raises ArgumentError for a value it doesn't know. With validate: true it becomes a normal validation error instead. Source: ActiveRecord::Enum (Rails API 8.1).

  4. Tag normalizes name to lowercase dashes. A tag saved before that, with plain SQL, has the name "Someday Maybe". What does Tag.find_by(name: "Someday Maybe") return?

    • The tag, because the query is not normalized
    • nil, because the query is normalized but the saved value isn't
    • The tag, with its name normalized on read
    Show answer

    nil, because the query is normalized but the saved value isn't. Normalization is not applied to values read from the database. Fix old records with normalize_attribute and save. Source: ActiveModel::Attributes::Normalization (Rails API 8.1).

Sources

Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.

Comments

Sign in to comment or sign up.