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?
The short answer is no. You will need to use a gem (such as magic-enum) if you want to do anything but store integers.
In DHH's own words on this from the comments on the pull request that added this feature:
How about:
It seems that with Rails 5 API only, an enum attribute of a model will be save in database as integer, but will be published in public API as a string (with ActiveModel::Serializer).
For example,
Article model:
Article serializer:
Will publish the following json:
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:
Altough with unexpected results when accessing it, see https://github.com/rails/rails/issues/16459
Update
This issue was fixed in Rails 5, see https://github.com/rails/rails/commit/c51f9b61ce1e167f5f58f07441adcfa117694301. Thanks Yuri.
As far as I know it's not possible with Active Record's built-in enum functionality. However, there are a few popular 3rd party gems that do this. The closest match to what comes with Active Record are probably enumerize and SimpleEnum.
However, if you're looking for something a little different, I'd recommend ClassyEnum (full disclosure: I wrote it). Here are some of my notes on the difference between enumerize and SimpleEnum vs ClassyEnum: