Search code examples
ruby-on-railsroutesadmin

How can I check user admin on routes.rb in Rails?


I have two different views and two different controllers in Rails app that I want the user to redirect to a specific one depending on whether a user is an admin or not.

I saw SO post like this one where it directs the page depending on whether user is authenticated or not, but I am looking for something like this (I am using devise):

#routes.rb
  authenticated :user do
    if user.admin
      root to: "admin/first_page#index", as: :authenticated_root
    else
      root to "first_page#index", as: :authenticated_root
    end
  end

  root to: "user/sign_in"

When the user signs in, it checks for user's admin privilege. If user is admin, go to admin/first_page#index. If user isn't admin, go to first_page#index.

I thought of using just one page and hide certain features for non-admin, something like: <% if user.admin%><%= secret_admin_feature %><% end %> to keep it dry, but I have my own reasons why I choose not to keep it dry in this case.

Is it possible to do admin check from routes.rb? If yes, how can it be done? If not, what is a good alternative?


Solution

  • I don't think it is a good idea to check for admin privileges in the routes. The proper way of doing it is as it follows:

    • You will have a application_helper method called is_admin? that checks if the user is an administrator or not.

    • You will submit your sign in form to a certain method. That is where you will need to use the helper and redirect.

    def sign_in
      # submit form and do your stuff here
      # and if your form submission was successful you would do something like this:    
      redirect_to admin_first_page_index_path and return if is_admin?
      redirect_to first_page_index_path and return
    end
    

    That is how I would do it.

    You still need to provide the redirect to the sign in page if your form submission failed. And in the admin/first_page#index method you might want to check if the user is admin and redirect to another page, just to force non admin users back into their flow.