Rails 5通过整数值获取枚举密钥

Sea*_*ean 3 ruby-on-rails ruby-on-rails-5

我有一个具有以下枚举的模型:

class User < ApplicationRecord
    enum user_type: [:api_user, :web_user]
end
Run Code Online (Sandbox Code Playgroud)

当它被保存到数据库中时,它会按预期使用整数值保存它.然后我有一个接受这样的枚举的函数(在控制器中):

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
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是选项[:type]传递整数值.我想通过整数获取User.user_type的键值.这可能吗?

再次感谢.

Sea*_*ean 13

好吧,做了一点搜索,发现了这个解决方案:

User.user_types.key(options[:type])
Run Code Online (Sandbox Code Playgroud)

这将返回密钥.

这是最简单的方法吗?还是另一种更好的解

  • 不推荐使用index,而使用`.key`代替. (2认同)