在ActionController中使用current_user

时间:2016-03-18 15:20:01

标签: ruby-on-rails ruby devise controller

我想从第三方gem中覆盖控制器的某些方法(从ActionController继承) 我的问题是我无法访问current_user,因为控制器没有从ApplicationController继承 有没有办法访问此控制器内的current_user?

修改

第三方宝石 - > spree_api

在spree_api中,对于每个请求,我们必须提供一个api_key,但我想使用一些不需要任何特殊权限的方法,访客用户可以调用它。所以我跳过这样的方法的身份验证:

module Spree
  module Api

    ProductsController.class_eval do
      skip_before_action :authenticate_user, :only => :index

      def index 
      ...
      current_user # -> undefined local variable or method `current_user'
      ....
      end
end

1 个答案:

答案 0 :(得分:0)

要查找当前用户控制器需要具有识别用户实体的内容。 在API的情况下,这个东西是api_key。 在大多数其他情况下,它通过浏览器发送带有请求头的令牌,该浏览器设计的current_user方法读取并识别用户。

您可以跳过不需要用户的用户身份验证(请求中的api_key),例如ProductsController等。但是你肯定需要用户(以及api_key),比如CheckoutController等其他用户。