Ruby-on-rails 如何从 Rails 中的枚举中获取整数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25570209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:52:57  来源:igfitidea点击:

How get integer value from a enum in Rails?

ruby-on-railsruby-on-rails-4

提问by Cleyton

I have a enum in my Model that corresponds to column in the database.

我的模型中有一个枚举,对应于数据库中的列。

The enumlooks like:

enum样子:

  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.

但这只会返回 0。

回答by Subtletree

You can get the integer like so:

你可以像这样得到整数:

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

Update for rails 5

Rails 5 的更新

For rails 5 the above method now returns the string value :(

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

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.

Shadwell 的回答也继续适用于 Rails 5。

回答by Shadwell

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 Modelclass to access the integer value for that instance:

然后,您可以使用Model类实例中的 sale_info 值来访问该实例的整数值:

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

回答by ArashM

Rails < 5

导轨 < 5

Another way would be to use read_attribute():

另一种方法是使用read_attribute()

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

Rails >= 5

导轨 >= 5

You can use read_attribute_before_type_cast

您可以使用 read_attribute_before_type_cast

model.read_attribute_before_type_cast(:sale_info)
=> 1

回答by Brilliant-DucN

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

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

回答by shrmn

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

我在我的模型中编写了一个方法来在我的 Rails 5.1 应用程序中实现相同的目标。

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