enum: turning a bare integer into a name you can read

Free preview 2 min to read

A column the earlier courses kept querying

Catalog::Course has a level column. This app's migration, db/migrate/20260226000001_create_courses.rb, defines it:

t.integer :level, null: false, default: 0
add_index :courses, :level

An integer, not null, defaulting to 0, indexed. Query the column directly and every course comes back as 0, 1, 2 or 3. Nothing in that result says which number means what. You'd have to find the migration, or a comment, or ask someone who remembers.

The same column, read through enum

app/models/catalog/course.rb has one extra line:

# app/models/catalog/course.rb
enum :level, { intern: 0, junior: 1, mid: 2, senior: 3 }

The column doesn't change. The database still stores 0 to 3 in an indexed integer column, as fast to query as any other. What changes is everything above the database: course.level now returns "junior", not 1, and setting course.level = "senior" writes 3. The mapping between name and number lives in one place, the model, instead of in someone's memory.

The shape of the declaration

In enum :level, { intern: 0, junior: 1, mid: 2, senior: 3 }, the first argument is the attribute name, matching a real column (level). The second is a hash: the name on the left, the integer stored in the column on the right. This app writes every one of its enums as an explicit hash, and lesson 6 covers why that matters once a mapping needs to change.

What this course covers

Seven lessons, all against code running in this app. The methods enum writes onto every instance come first (lesson 2), then the ones it writes onto the class, including a mapping you can query directly (lesson 3). Lesson 4 has two traps, one that protects you and one that quietly doesn't. Lesson 5 covers what enum does and doesn't validate on its own, and lesson 6 shares one mapping across two models instead of retyping it. The closing lesson puts every enum in this app into one picture.

This app declares ten of them on eight models, covering things from a course's difficulty level to a partner's sponsorship tier. Most of them show up somewhere in the next six lessons.

Lesson 1 of 7 · free

Keep going with lesson 2

The methods enum writes for you: ?, !, and reading the name back

The ? and ! methods enum generates for each name, as used by the service that completes an enrollment.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...