4

I have a model that has the follow enum:

class User < ApplicationRecord
    enum user_type: [:api_user, :web_user]
end

When this gets saved into the database, it saves it with the integer value, as expected. I then have a function that accepts the enum like this (in a controller):

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

The problem I'm encountering is that the options[:type] is passing the integer value. I'd like to get the key value of User.user_type by the integer. Is this possible?

Thanks again.

2
  • Since you're passing in a user object, and, assuming that it has been assigned a user_type, why don't you interrogate it directly to see what user type it is? user.user_type => "web_user" Commented Jul 30, 2016 at 6:11
  • Possible duplicate of in Ruby, how to extract a key from the Hash having the value Commented Jul 1, 2017 at 13:11

1 Answer 1

16

Well, did a bit more searching and found this solution:

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

This will return the key.

Is this the easiest way? Or another better solution?

Sign up to request clarification or add additional context in comments.

2 Comments

now index method will be deprecated. You should be used the key method. Just updating.
index is deprecated, use .key instead, is the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.