2016-07-29 33 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',是一樣的。 –