How get integer value from a enum in Rails?

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.

76999 次浏览

可以从枚举所在的类中获取枚举的整数值:

Model.sale_infos # Pluralized version of the enum attribute name

That returns a hash like:

{ "plan_1" => 1, "plan_2" => 2 ... }

然后,您可以使用来自 Model类的实例的 sales _ info 值来访问整数值 比如说:

my_model = Model.find(123)
Model.sale_infos[my_model.sale_info] # Returns the integer value

你可以这样得到整数:

my_model = Model.find(123)
my_model[:sale_info] # Returns the integer value

更新铁轨5

对于 Rails5,上面的方法现在返回字符串值: (

目前我能想到的最好的办法是:

my_model.sale_info_before_type_cast

Shadwell 的回答同样适用于 Rails5。

铁路 < 5

另一种方法是使用 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

如果你想得到 plan_2的值,我的简短回答是 Model.sale_infos[:plan_2]

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

针对您的情况,将其添加到您的模型中,并在需要时对对象调用它

def numeric_sale_info
self.class.sale_infos[sale_info]
end

这里的大多数解决方案都要求您拥有一个记录或模型类。下面是一种方法,通过使用 Hash 的 .key方法,您可以在不创建记录的情况下从枚举中获取整数值:

sale_info.key('plan_3')
=> 3

如果您正在执行某些 ETL 操作,并在依赖于数字整数值和/或不同场景中的字符串值的系统之间将原始值映射到/从字符串值映射,那么这种方法特别有用。

请注意,这可能不是高性能的,因为在散列中搜索值(相对于键)效率不高。如果您正在处理数百万个值/秒,或者有一个包含数百个值的枚举,那么您可能需要构建一个新的散列来反转枚举的值和键,这样您就可以在相反的方向进行高效的查找。