I have a enum in my Model that corresponds to column in the database.
The enum looks like:
enum sale_info: { plan_1: 1, plan_2: 2, plan_3: 3, plan_4: 4, plan_5: 5 } How can I get the integer value?
I've tried
Model.sale_info.to_i But this only returns 0.
No, we can have only strings as elements in an enumeration.
Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.
You can get the integer values for an enum from the class the enum is on:
Model.sale_infos # Pluralized version of the enum attribute name That returns a hash like:
{ "plan_1" => 1, "plan_2" => 2 ... } You can then use the sale_info value from an instance of the Model class to access the integer value for that instance:
my_model = Model.find(123) Model.sale_infos[my_model.sale_info] # Returns the integer value
You can get the integer like so:
my_model = Model.find(123) my_model[:sale_info] # Returns the integer value Update for rails 5
For rails 5 the above method now returns the string value :(
The best method I can see for now is:
my_model.sale_info_before_type_cast Shadwell's answer also continues to work for rails 5.
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