How to create a dynamic root in Rails 3?

你说的曾经没有我的故事 提交于 2019-12-04 05:29:26

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.

Blair Anderson

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

You can't truly change the root dynamically, but there's a couple of ways you can fake it.

The solution you want needs to take place in either your application controller or the "default" root controller. The cleanest/easiest solution is simply to have your application controller redirect to the appropriate action in a before filter that only runs for that page. This will cause the users' url to change, however, and they won't really be at the root anymore.

Your second option is to have the method you've specified as root render a different view under whatever conditions you're looking for. If this requires any major changes in logic beyond simply loading a separate view, however, you're better off redirecting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!