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?
We can convert an enum to string by calling the ToString() method of an Enum.
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
An Enum value cannot be treated as an int by default because then you would be able to provide any integer and there would be no compile time check to validate that the provided integer does in fact exist as a value in the Enumeration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With