基于条件的Rails路线 [英] Rails Routes based on condition
问题描述
我有三个角色:Instuctor,Student,Admin,每个角色都有带有主视图的控制器。
I have three roles: Instuctor, Student, Admin and each have controllers with a "home" view.
所以这很好用,
get "instructor/home", :to => "instructor#home"
get "student/home", :to => "student#home"
get "admin/home", :to => "admin#home"
我想编写一个虚荣网址,如下所示,它将根据角色进行路由 user_id
到正确的首页。
I want to write a vanity url like below which will route based on the role of the user_id
to the correct home page.
get "/:user_id/home", :to => "instructor#home" or "student#home" or "admin#home"
我如何完成
推荐答案
您无法对路由执行此操作,因为路由系统没有做出此决定所需的信息。在请求的这一点上,所有Rails都知道参数是什么,并且不能访问数据库中的任何东西。
You can't do this with routes because the routing system does not have the information required to make this decision. All Rails knows at this point of the request is what the parameters are and does not have access to anything in the database.
您需要的是一个可以加载的控制器方法任何需要的数据,大概是用户记录,并使用 redirect_to
进行相应的重定向。
What you need is a controller method that can load whatever data is required, presumably the user record, and redirects accordingly using redirect_to
.
这是相当标准的事情
更新:
要在单个时间内执行所有这些操作控制器动作,您将需要根据角色拆分逻辑。例如:
To perform all of this within a single controller action you will need to split up your logic according to role. An example is:
class HomeController < ApplicationController
def home
case
when @user.student?
student_home
when @user.admin?
admin_home
when @user.instructor
instructor_home
else
# Unknown user type? Render error or use a default.
end
end
protected
def instructor_home
# ...
render(:template => 'instructor_home')
end
def student_home
# ...
render(:template => 'student_home')
end
def admin_home
# ...
render(:template => 'admin_home')
end
end
这篇关于基于条件的Rails路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!