Rails使用嵌套资源路由根
我的routes.rb
有一个嵌套资源,如下所示:
map.resources :users, :only => [:index] do |user| user.resources :projects end
这给了我像/users/2/projects
这样的URL,它将显示user
2拥有的所有项目。用户登录后,我希望使用map.root
作为根页面。 我如何设置map.root
来启用它? 我正在使用设计,所以我可以使用current_user
获取当前用户,但我不确定它在routes.rb
是否可用。
我们正在使用一个HomepageController来解决这个问题,该ControllerController根据if current_user
呈现两个不同的模板。
您将路由设置到RootController
中的RootController
控制器以及现有嵌套路由:
map.root :controller => :root
然后,控制器RootController
的index
操作可以呈现ProjectsController
的index
操作:
class RootController < ApplicationController def index render :controller => :projects, :action => :index end end
最后, ProjectsController
将使用current_user
来呈现适当的项目列表:
class ProjectsController < ApplicationController def index @projects = Project.all.find_by_user(current_user) end end
这掩盖了认证等细节。
您可以在filter方法中进行身份validation后重定向到该页面:
redirect_to user_projects_path(logged_in_user)