Rails Devise current_user 在匹配项中未定义?高级路由约束 [英] Rails Devise current_user is undefined in a matches? advanced route constraint
问题描述
我收到错误 NameError(未定义的局部变量或方法current_user" for #
当我尝试在 匹配项中使用 current_user 时? 约束.我希望某些虚拟用户被路由到一组控制器,而其他用户被路由到另一组控制器.但是,当我尝试使用 current_user 时出现错误.
I get an error NameError (undefined local variable or method "current_user" for #<APIRouter:0x007ffd54a81f98>):
when I try to use current_user in a matches? constraint. I want certain dummy user to be routed to one set of controllers and other users to be routed to another set of controllers. However, when I try to use current_user I get an error.
- 设计 (2.0.4)
- 导轨 (3.2.2)
我的匹配约束在 APIRouter 类中定义:
My matches constraint is defined in the APIRouter Class:
class APIRouter
def matches? request
@use_rm_app = ENV["USE_RM_APP"] == "true" || (current_user && current_user.is_test)
end
end
关于如何在比赛中使用当前用户的任何想法?Rails 指南中定义的约束.
Any ideas as to how I can use current user in the matches? constraint as defined in the Rails guide.
来自 routes.rb 文件的部分:
Section from the routes.rb file:
# Route to the rm_app controller if APIRouter says we should, otherwise use the real backend controllers.
match '/api/v1/*path', :controller => 'api/v1',
:action => 'handle_create_request',
:via => :post, :constraints => APIRouter.new
更新:感谢 ksol 解决. 尝试 3 有效.使用 request.env["warden"].user(:user)
解决办法是修改APIRouter
Solution is to modify the APIRouter
def matches? request
user = request.env["warden"].user(:user)
(user && user.is_test) || ENV["USE_RM_APP"] == "true"
end
推荐答案
current_user
仅在您的控制器和视图中可用.实现您想要的目标的方法不止一种,将其作为参数提供给您的方法越容易.
current_user
is only available in your controllers and views. There is more than one way to achieve what you want, the easier being supplying it as a parameter to your method.
编辑
如果 current_user
如果在路由器中可以访问,您可以通过执行 constraints: APIRouter.new(current_user)
将其传递给您的约束类.然后您需要定义 APIRouter#initialize
并将 current_user 存储在您可以在 matches?
中使用的实例变量中.
if current_user
if accessible in the router, you can pass it to your constraints class by doing constraints: APIRouter.new(current_user)
. Then you need to define APIRouter#initialize
and store the current_user in an instance var that you can use in matches?
.
编辑 2
我只记得设计允许您在路由器中执行此操作:
I just remembered devise allows you to do this in your router :
authenticated :user do
root :to => "main#dashboard"
end
我不知道如何确保user.is_test
.
编辑 3
最后一次尝试.request.env["warden"].user(:user)
应该给你一个用户,如果一个用户通过身份验证.
Last attempt. request.env["warden"].user(:user)
should give you a user if one is authenticated.
这篇关于Rails Devise current_user 在匹配项中未定义?高级路由约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!