枚举密钥我有了后续枚举的模型:的Rails 5获得通过整数值
class User < ApplicationRecord
enum user_type: [:api_user, :web_user]
end
当这个被保存到数据库中,它具有整数值将其保存,符合市场预期。然后,我有接受这样的枚举(在控制器中)的函数:
do_something_useful(type: User.user_types[:web_user], user: user)
def do_something_useful(options)
some_enum_value = options[:type]
user = options[:user]
# Not a practical example. Just an example to demonstrate the issue.
# Should return Hello, User! You are a web_user type.
# But returns, Hello, User! You are a 1 type.
'Hello, #{user.name}! You are a #{some_enum_value} type.'
end
我遇到的问题是,这些选项[:类型]时使整数值。我想通过整数获取User.user_type的关键值。这可能吗?
再次感谢。
既然你传递了一个'user'对象,并且假设它已经被赋予'user_type',为什么不直接询问它以查看它是什么用户类型? 'user.user_type =>“web_user”' –
[在Ruby中可能的重复,如何从具有值的哈希中提取密钥](https://stackoverflow.com/questions/13184752/in-ruby-how-to -extract-a-key-from-the-has-the-value) –