枚舉密鑰我有了後續枚舉的模型:的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) –