我提供了一种替代方法,因为在 Rails 中搜索基于角色的路由时,这个问题出现在顶部附近。
我最近需要实现类似的东西,但希望避免控制器中存在大量条件 - 由于我的每个用户角色都需要加载和呈现完全不同的数据,这一事实使情况变得更加复杂。我选择使用以下方法将决策逻辑移至路由层路由约束 http://guides.rubyonrails.org/routing.html#advanced-constraints.
# 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
对象,其中包含有关所发出请求的各种信息。就我而言,我正在查找:user_id
存储在会话 cookie 中并使用它来查找发出请求的用户。
然后,您可以在定义路线时使用此约束。
# 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
将被路由到home的行动AdministratorsController
,一位讲师提出请求/home
将被路由到home的行动InstructorsController
,以及一名学生提出请求/home
将被路由到home的行动StudentsController
.
更多信息
如果您正在寻找更多信息,我最近在my blog http://bjedrocha.com/rails/2015/03/18/role-based-routing-in-rails/.