A Simple Guide to Enum’s with Rails

black and white dappled light on leaves
black and white dappled light on leaves

What

Why

When

How

Setting up an enum

rails g model Task description:string status:integer
class Task < ActiveRecord::Base
enum status: [ :not_started, :in_progress, :complete ]
end
class Task < ActiveRecord::Base
enum status: {in_progress: 1 , complete: 2, not_started: 0 }
end
// both ways set "not_started" = 0, "in_progress" = 1, "complete" = // 2

Working with an enum

> task.status = 1; task.status
=> "in_progress"
> task.status = "in_progress"; task.status
=> "in_progress"
> task.in_progress!
=> true
> task.status
=> "in_progress"
> task.status
=> "in_progress"
> task.first.in_progress?
=> true
> Task.in_progress
TaskLoad (0.3ms) SELECT "tasks".* FROM "tasks" WHERE "taskes"."status" = ? [["status", 1]]
// ../form.html.erb<div class="field">
<%= f.label :status %><br>
<%= f.select :status, Phone.status.keys %>
</div>

Written by

Full-Stack Software Engineer, Designer, and salsa dancer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store