1

I've got a user model in rails which includes an attribute authorization. I want to design it as an enum which holds the authorization level of the user:

class User < ApplicationRecord    
  enum authorization: [default: 0, moderator: 1, admin: 2]
  # User code
end

Afterwards I added some methods into my application controller which I want to user in order to verfiy the authorization status of the user in the other controllers.

#Application Controller

def moderator_required
  return redirect_to root_path if current_user.nil?
  redirect_to root_path if !current_user.admin? && !current_user.moderator?
end

def admin_required
  return redirect_to root_path if current_user.nil?
  redirect_to root_path unless current_user.admin?
end

I found the shortcut user.admin? in the Documentation.

Even though I get the following error when trying to use the admin_required method:

undefined method `admin?' for #<User:0x7091e20>

Does anyone have an idea what I'm missing here?

2 Answers 2

5

You're using hash. Try changing your enum declaration to:

enum authorization: { default: 0, moderator: 1, admin: 2 }
Sign up to request clarification or add additional context in comments.

2 Comments

I will go to bed now... Thank you very much, this is the reason why we need more coffee for developers.
Sure, I just need to wait a few minutes until I can.
1

Starting from zero and increment by one is the default so you don't even need an hash. This is the same

enum authorization: [:default, :moderator, :admin]

Comments

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.