How to create a dynamic root in Rails 3?

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

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

Can someone connect me with an example that can show me the direction? Is there a way to put logic in a routes file? Thanks for the help.

+5
source share
3 answers

You can simply create a controller for the 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 route.rb:

  root 'routes#root'

PS example expects to use Devise , but you can customize it for your needs.

+5

:

1. lambda ( )

2. before ( , )

-

. , HomeController, AdminController. index.

config/routes.rb

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

root to: "home#index"

/admin, '/'

, ; before_filter , admin.

3. .

, , , .

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

admin.html.erb

: -

+2

- , .

, , , . / - , . , URL- , .

The second option is to specify a method that you specified as root that displays a different view in whatever conditions you are looking for. However, if this requires any major changes to the logic, other than just loading a separate view, you should redirect it.

0
source

All Articles