ActiveRecord: enums
This course covers Rails enums through the code of one app. It starts with an integer level column and the enum line that maps each stored number to a name. Next come the ? and ! methods on instances. Then come the class scopes and the plural mapping hash, which reads in both directions. The course shows why assignment raises on a bad value while .where quietly matches nothing. It also covers what enum validates by default, the validate option, and sharing one mapping across models.
What you'll learn
- ✓How an enum declaration maps integer column values to names
- ✓The ? and ! instance methods and the class scopes enum generates
- ✓Reading the plural mapping hash from name to integer and back
- ✓Why assignment raises on an invalid value while .where does not
- ✓What enum validates on its own and how the validate option changes it
- ✓Reusing one mapping across models with prefix, and why to use explicit hashes
enum: turning a bare integer into a name you can read
Catalog::Course has a level column. This app's migration, db/migrate/20260226000001_create_courses.rb, defines it:
Read the full lesson free →Curriculum
7 lessonsenum: turning a bare integer into a name you can read
How enum maps the integer level column of Catalog::Course to readable names, declared as an explicit hash.
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.
Course.junior and the .levels hash: enum on the class
The scopes enum adds to the class and the plural mapping hash, read from name to integer and back.
The trap: assignment raises on a bad value, .where doesn't
Assigning an invalid enum value raises ArgumentError, while the same value in .where becomes a condition matching nothing.
What enum validates on its own, and what this app adds
A plain enum lets nil through, and the validate option, including allow_nil, moves the check into validation.
One mapping, two models: reusing an enum hash instead of retyping it
Reusing one model's generated mapping hash in another model, with prefixes, and why every enum uses explicit hashes.
Putting it together: this app's ten enums, side by side
A table of the app's ten enums on eight models, plus the default and prefix: true options.