Rails Devise current_user在匹配中未定义?高级路由约束 [英] Rails Devise current_user is undefined in a matches? advanced route constraint

查看:294
本文介绍了Rails Devise current_user在匹配中未定义?高级路由约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个错误 NameError(未定义的局部变量或方法current_user为#< APIRouter:0x007ffd54a81f98>):当我尝试使用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.


  • devise(2.0.4)

  • rails(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。 / strong>尝试3作品。获取用户使用 request.env [warden]。user(:user)

UPDATE: Solved thanks to ksol. Attempt 3 works. Get user using 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 如果在路由器中可访问,则可以通过执行约束将其传递给约束类:APIRouter.new(current_user)。然后,您需要定义 APIRouter#initialize 并将current_user存储在您可以在匹配中使用的实例var中。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆