Rails, Devise. Disallow User actions unless AdminU

2019-07-27 13:50发布

问题:

I have User model created with Devise, with type:string attribute and a AdminUser model (AdminUser < User).

In application controller I defined the :require_admin method:

  def require_admin
    unless current_user == AdminUser
      flash[:error] = "You are not an admin"
      redirect_to store_index_path
    end
  end

On products controller I set

before_action :require_admin, except: :show

Now I create an AdminUser via console successfully (with AdminUser id) and when I log in the app, I still can not use those actions (create, edit etc.).

Any ideas?

回答1:

With

current_user == AdminUser

you check whether current_user object is equal to the AdminUser class.

What you want instead is to check whether current_user's class is AdminUser:

current_user.class == AdminUser
# or
current_user.is_a?(AdminUser)
# or
current_user.kind_of?(AdminUser)
# or
current_user.instance_of?(AdminUser)
# or
AdminUser === current_user


回答2:

I believe it should be current_user.is_a?(AdminUser)

Source : is_a? method documentation