What is the best way to add ENUM fields in the Rails 4 model?

3

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

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
    
asked by anonymous 18.03.2014 / 14:51

1 answer

1

So:

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

Searches

# 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
    
18.03.2014 / 16:04