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

Asked

Viewed 341 times

3

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

What’s the best way to do that?

models/item.Rb

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

   # ???
end

controllers/list.Rb

class ListaController < ApplicationController
   # preciso buscar algo assim:
   Item.status
   Item.status.publicado
   Item.status.suspenso
   Item.status.something
end
  • has something here : http://rails-bestpractices.com/posts/708-clever-enums-in-rails

1 answer

1


Thus:

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
  • Opa, that’s right, I was trying so, but I found that this option is only available in Rails 4.1+.

  • Do you want the answer to any specific version of Rails?

  • No, it worked! My Rails, it was 4.0. I upgraded to 4.1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.