Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dynamic root in Rails 3?

I have admins and normal users in my webapp. I want to make their root (/) different depending on who they are. The root is accessed from many different pages, so it would be much easier if I could make this happen in the routes.rb file. Here is my current file.

ProjectManager::Application.routes.draw do
  root :to => "projects#index"
end

Can someone please link me to an example that can show me the direction to go in? Is there any way to put logic into the routes file? Thanks for all the help.

like image 861
jhamm Avatar asked Aug 14 '12 21:08

jhamm


2 Answers

You can just create controller for root route.

class RoutesController < ActionController::Base
  before_filter :authenticate_user!

  def root
    root_p = case current_user.role
      when 'admin'
        SOME_ADMIN_PATH
      when 'manager'
        SOME_MANAGER_PATH
      else
        SOME_DEFAULT_PATH
      end

    redirect_to root_p
  end
end

In your routes.rb:

  root 'routes#root'

P.S. example expects using Devise, but you can customize it for your needs.

like image 74
Andrey Skuratovsky Avatar answered Sep 22 '22 00:09

Andrey Skuratovsky


There are a few different options:

1. lambda in the routes file(not very railsy)

previously explained

2. redirection in application controller based on a before filter(this is optimal but your admin route will not be at the root)

source rails guides - routing

you would have two routes, and two controllers. for example you might have a HomeController and then an AdminController. Each of those would have an index action.

your config/routes.rb file would have

namespace :admin do
  root to: "admin#index"
end

root to: "home#index"

The namespace method gives you a route at /admin and the regular root would be accessible at '/'

Then to be safe; in your admin controller add a before_filter to redirect any non admins, and in your home controller you could redirect any admin users.

3. dynamically changing the layout based on user role.

In the same controller that your root is going to, add a helper method that changes the layout.

layout :admin_layout_filter
private
def admin_layout_filter
  if admin_user?
    "admin"
  else
    "application"
  end
end

def admin_user?
  current_user.present? && current_user.admin?
end

Then in your layouts folder, add a file called admin.html.erb

source: rails guides - layouts and routing

like image 24
Blair Anderson Avatar answered Sep 19 '22 00:09

Blair Anderson