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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With