Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 get enum key via integer value

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.

like image 270
Sean Avatar asked Dec 05 '22 17:12

Sean


1 Answers

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?

like image 181
Sean Avatar answered Dec 11 '22 09:12

Sean