Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possibility of mapping enum values to string type instead of integer

Tags:

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?

like image 916
Eren CAY Avatar asked Jun 08 '14 11:06

Eren CAY


People also ask

Can enum be converted to string?

We can convert an enum to string by calling the ToString() method of an Enum.

Can enum have string values?

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.

How do I assign an enum to a string?

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.

Can enum be treated as int?

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.


1 Answers

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.

like image 124
Mihai Târnovan Avatar answered Oct 21 '22 14:10

Mihai Târnovan