Blankman
Blankman

Reputation: 266978

How to get the int value from my Model enum when I have an record instance?

How can I convert a Model enum to the INT value?

I am trying to do this:

class User < ActiveRecord::Base
  enum user_type: [:member, :super]
end

Now say I have a user record, now I want to use the user_type enum value in another query:

u = User.find_by_type(@user.user_type)

def self.find_by_user_type(user_type)
  User.where(user_type: user_type).take
end

This doesn't work because the user.user_type is returning "member" or "super" and I need 0 or 1.

Is there a way to get the Int value from my @user instance?

(Rails 4.x)

Upvotes: 3

Views: 2974

Answers (1)

Mark
Mark

Reputation: 10998

To get integer equivalent of enum type:

User.user_types[self.user_type] # returns integer value

Replace self with another user instance if necessary.

Upvotes: 5

Related Questions