1

The Rails 4 enum implementation is rather nice for making a status field such as

class User < ActiveRecord::Base
  enum status: [:goodstanding, :outstanding]

But if I want to display text depending on the status, this text mapping should be in one place and the enum doesn't offer a solution to map to text.

Here is what I had before

class User < ActiveRecord::Base
  STATUS = {
    :outstanding => "Outstanding balance",
    :goodstanding => "In good standing"
  }

Which allowed me to do

User::STATUS[user.status] # "In good standing"

to display my text. Any suggestions on how to do this with the newer enum type?

TheJKFever
  • 685
  • 7
  • 25

1 Answers1

2

Yes this can be done in rails 4.1+, but it behaves unexpectedly, and has been fixed in rails 5 branch.

Source: https://github.com/rails/rails/issues/16459

For example:

class User
  enum name: {
    foo: 'myfoo',
    bar: 'mybar'
  }
end

Now when you do:

u = User.new(name: 'foo')
u.save

Then it will execute:

INSERT INTO `users` (`name`, `created_at`, `updated_at`) VALUES ('myfoo', '2015-07-20 04:53:16', '2015-07-20 04:53:16')

For foo it inserted myfoo. Now when you do:

u = User.last

u.name
 => "foo"

u[:name]
 => "myfoo"

I have tried the above. Whlie there are various gems available too, I have never used them but may be they help you:

  1. enumerize
  2. simple_enum
  3. classy_enum

Source: Possibility of mapping enum values to string type instead of integer

Hope this helps.

Community
  • 1
  • 1
Deepesh
  • 6,138
  • 1
  • 24
  • 41
  • +1 for fixed in Rails 5. I saw this answer elsewhere, and have seen a couple of these gems (not enumerize). I just didn't want to use a gem for this. Looking forward to it in Rails 5, thanks. – TheJKFever Jul 20 '15 at 05:34
  • Can someone update this with a better example like the question? as a newbie, this example is very confusing. – Jay Aug 22 '20 at 17:05