我提供了另一种方法,因为在 Rails 中搜索基于角色的路由时,这个 SO 问题出现在顶部附近。
我最近需要实现类似的东西,但想避免在控制器中包含大量条件 - 由于我的每个用户角色都需要加载和呈现完全不同的数据,这使情况更加复杂。我选择使用Routing Constraint 将决定逻辑移至路由层。
# app/constraints/role_route_constraint.rb
class RoleRouteConstraint
def initialize(&block)
@block = block || lambda { |user| true }
end
def matches?(request)
user = current_user(request)
user.present? && @block.call(user)
end
def current_user(request)
User.find_by_id(request.session[:user_id])
end
end
上述代码中最重要的部分是matches? 方法,它将确定路由是否匹配。该方法传递了request 对象,该对象包含有关正在发出的请求的各种信息。就我而言,我正在查找存储在会话 cookie 中的 :user_id 并使用它来查找发出请求的用户。
然后,您可以在定义路线时使用此约束。
# config/routes.rb
Rails.application.routes.draw do
get 'home', to: 'administrators#home', constraints: RoleRouteConstraint.new { |user| user.admin? }
get 'home', to: 'instructors#home', constraints: RoleRouteConstraint.new { |user| user.instructor? }
get 'home', to: 'students#home', constraints: RoleRouteConstraint.new { |user| user.student? }
end
有了上述内容,向/home 发出请求的管理员将被路由到AdministratorsController 的home 操作,向/home 发出请求的教师将被路由到InstructorsController 的 home 动作,以及向 /home 发出请求的学生将被路由到 StudentsController 的 home 动作。
更多信息
如果您正在寻找更多信息,我最近在my blog 上写了关于这种方法的文章。