Search code examples
ruby-on-railsdevise

Devise admin routes


I have a devise User and inside I have admin as boolean default to false. How can I fixed my routes in my ruby on rails app for it to give access to certain pages ONLY for the admin who has admin as true.

UPDATE: I changed followed the first answer I got which said to create a is_admin? method in my controller and specify what actions. However, when I do that, I get a:

undefined method `admin' for nil:NilClass

UPDATE 2:

Products Controller:

class ProductsController < ApplicationController
  before_action :is_admin?, only: [:edit, :update, :destroy]
  before_action :set_product, only: [:show]

Application Controller:

def is_admin?
  if signed_in?
    redirect_to root_path unless current_user.admin
  end
end

Solution

  • You shouldn't do that in the routes file, the best place to do it's on the controller filtering part. Attention to the :authenticate_user! method being before the is_admin?. Otherwise current_user will be nil.

    class PagesController < ApplicationController
       before_action :authenticate_user!
       before_action :is_admin?, only: [:action1, :action2]
       ...
      
       private
       
       def is_admin?
         unless current_user.is_admin?
           flash.alert = "Sorry, you don't have permissions to perform this action."
           redirect_to root_path
         end
       end
    end