基于条件的 Rails 路线 [英] Rails Routes based on condition
问题描述
我有三个角色:教师、学生、管理员,每个角色都有带有主页"视图的控制器.
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"
我想写一个如下所示的虚 url,它将根据 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
.
这是一个相当标准的事情.
This is a fairly standard thing to do.
更新:
要在单个控制器操作中执行所有这些操作,您需要根据角色拆分逻辑.一个例子是:
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屋!