Possibility of mapping enum values to string type instead of integer

Eren CAY picture Eren CAY · Jun 8, 2014 · Viewed 23.1k times · Source

Enum attributes are great and I want to use them. But mapping enum values to integer would make it hard to maintain both code and database. Also my database would be highly coupled with my code which I think I should consider that a bad thing.

I know I can use a hash to organize an enum attribute with key/value pairs, but still it would be a lot better to be able to use an array and map to string values in database.

Is there any way to map enum to strings by default?

Answer

Mihai Târnovan picture Mihai Târnovan · Nov 2, 2014

Looking at the code for enum, you can do this (at least in 4.1+): https://github.com/rails/rails/blob/master/activerecord/lib/active_record/enum.rb#L96-98 by passing a hash, for example:

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

Altough with unexpected results when accessing it, see https://github.com/rails/rails/issues/16459

foo_instance.foo!
foo_instance.name
=> "foo"
foo_instance[:name]
=> "myfoo"

Update

This issue was fixed in Rails 5, see https://github.com/rails/rails/commit/c51f9b61ce1e167f5f58f07441adcfa117694301. Thanks Yuri.