Nikolay's Blog

Rails Enum Tutorial

Cover Image for Rails Enum Tutorial
  • Created at:
  • Updated at:
  1. Generate migration by running command:
$ rails g migration AddStatusToUsers status
  1. ./db/migrations/xxx_migration.rb
def change
  add_column :users, :status, :string, null: false, default: 'unverified'
  add_index :users, :status
end
  1. ./app/models/user.rb
class Users < ApplicationRecord
  enum status: {
    claimed:    'claimed',
    unverified: 'unverified',
    verified:   'verified',
  }

  validates :status, inclusion: { in: statuses.keys }
end
  • ā“ Why statuses are strings not integers?
  • A:
    1. Raw sql queries seems more human readable.
    2. Code is also much human readable.
    3. You don't need to calculate next value
    4. You can easily add/remove/sort values
    5. No performance degrade if index was added
  • ā“ Why statuses are strings not symbols
  • A: Values must be strings not symbols! (šŸ› claimed: :claimed does not work correctly)

Enums Set Default Values

If we specified default: 'unverified' in migration above, we don't need to use before_validation. If you didn't then do

  • ā“ Why not to use before_validation callback to set default value?
  • A: Rails handles deafult: value well and thus code seems much clearer

Enums Which statuses need to avoid

I'm not totally sure in it, but sometimes the following statuses conflicts with existing ones, so try to avoid it

  • changed
  • initial
  • parents
  • kind
  • type