How get integer value from a enum in Rails?

Ruby on-RailsRuby on-Rails-4

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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.

Solution 3 - Ruby on-Rails

Rails < 5

Another way would be to use read_attribute():

model = Model.find(123)
model.read_attribute('sale_info')

Rails >= 5

You can use read_attribute_before_type_cast

model.read_attribute_before_type_cast(:sale_info)
=> 1

Solution 4 - Ruby on-Rails

My short answer is Model.sale_infos[:plan_2] in case if you want to get value of plan_2

Solution 5 - Ruby on-Rails

I wrote a method in my Model to achieve the same in my Rails 5.1 app.

Catering for your case, add this into your Model and call it on the object when needed

def numeric_sale_info
  self.class.sale_infos[sale_info]
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCleytonView Question on Stackoverflow
Solution 1 - Ruby on-RailsShadwellView Answer on Stackoverflow
Solution 2 - Ruby on-RailsSubtletreeView Answer on Stackoverflow
Solution 3 - Ruby on-RailsArashMView Answer on Stackoverflow
Solution 4 - Ruby on-RailsBrilliant-DucNView Answer on Stackoverflow
Solution 5 - Ruby on-RailsshrmnView Answer on Stackoverflow