简体   繁体   中英

Ruby on Rails Enum Undefined method

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?

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

enum authorization: { default: 0, moderator: 1, admin: 2 }

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM