简体   繁体   中英

Rails before action check if admin

I installed devise and I've added to the user table a record or column (I'm not sure how to call it) a admin:boolean and by default it's false

In my routes.rb I have created this /admin link

get 'admin' => 'admin#index'

and I'm not sure how to show it only for admin

class AdminController < ApplicationController
  before_action: I have no idea what to write here

  def index
  end

end

Try like this in your controller:

class AdminController < ApplicationController
    before_action :is_admin?

  def index

  end


    # it will call before every action on this controller
    def is_admin?
      # check if user is a admin
      # if not admin then redirect to where ever you want 
      redirect_to root_path unless current_user.admin? 
    end

end

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