ruby-on-rails – What is the best way to add ENUM fields in Rails 4 model?

Question:

I need to reference the database status field numbers, which are in ENUM format, to my model names.

What is the best way to do this?

models/item.rb

class Item < ActiveRecord::Base
   # definir constantes
   PUBLICADO = 1
   SUSPENSO  = 2
   SOMETHING = 3

   # ???
end

controllers/lista.rb

class ListaController < ApplicationController
   # preciso buscar algo assim:
   Item.status
   Item.status.publicado
   Item.status.suspenso
   Item.status.something
end

Answer:

So:

class Item < ActiveRecord::Base
   enum status: { publicado: 1, suspenso: 2, something: 3 }
end

Looking for

# item.update! status: 1
item.publicado!
item.publicado? # => true
item.status # => "publicado"

# item.update! status: 2
item.suspenso!
item.suspenso? # => true
item.status    # => "suspenso"

# item.update! status: 1
item.status = "publicado"

# item.update! status: nil
item.status = nil
item.status.nil? # => true
item.status      # => nil
Scroll to Top