如何从 Rails 中的枚举中获取整数值? [英] How get integer value from a enum in Rails?

查看:49
本文介绍了如何从 Rails 中的枚举中获取整数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

enum 看起来像:

  enum sale_info: { plan_1: 1, plan_2: 2, plan_3: 3, plan_4: 4, plan_5: 5 }

如何获取整数值?

我试过了

Model.sale_info.to_i

但这只会返回 0.

推荐答案

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

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

返回一个哈希值,如:

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

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

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

这篇关于如何从 Rails 中的枚举中获取整数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆