2016-07-29 3 views
1

経由列挙型のキーを取得します5。 【:タイプ】整数値を渡して私が遭遇だ問題は、オプションがあることRailsは私がフォロー列挙型を持つモデルを持っている整数値

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-value-has-the-value) –

答えて

3

まあ、もう少し検索を行なったし、この解決策を見つけた:

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

これは、キーを返します。

これが最も簡単な方法ですか?それとももっと良い解決策ですか?

+0

indexメソッドは廃止予定です。重要な方法を使用する必要があります。ちょうど更新する。 – Hamdan

+1

インデックスは廃止予定で、代わりに '.key'を使用します。 –

関連する問題