Rails 5 get enum key via integer value

12,530

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?

Share:
12,530
Sean
Author by

Sean

I be programmer. I write big things. I like pretty stuff. I have staff. Sad they must be.

Updated on June 28, 2022

Comments

  • Sean
    Sean almost 2 years

    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.

  • Hamdan
    Hamdan over 7 years
    now index method will be deprecated. You should be used the key method. Just updating.
  • Arnold Roa
    Arnold Roa over 7 years
    index is deprecated, use .key instead, is the same.