2016-07-29 43 views
1

枚举密钥我有了后续枚举的模型:的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的关键值。这可能吗?

再次感谢。

+0

既然你传递了一个'user'对象,并且假设它已经被赋予'user_type',为什么不直接询问它以查看它是什么用户类型? 'user.user_type =>“web_user”' –

+0

[在Ruby中可能的重复,如何从具有值的哈希中提取密钥](https://stackoverflow.com/questions/13184752/in-ruby-how-to -extract-a-key-from-the-has-the-value) –

回答

3

嗯,确实有点多的搜索,发现此解决方案:

User.user_types.key(options[:type]) 

这将返回键。

这是最简单的方法吗?或另一个更好的解决方案

+0

现在index方法将被弃用。你应该使用关键的方法。只是更新。 – Hamdan

+1

索引已弃用,请改用'.key',是一样的。 –