TheJKFever
TheJKFever

Reputation: 705

Rails enum mapping to displayable text

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?

Upvotes: 2

Views: 1291

Answers (1)

Deepesh
Deepesh

Reputation: 6398

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.

Upvotes: 2

Related Questions