如何访问序列化程序内部ApplicationController中定义的@current_user变量

问题描述 投票:0回答:1

我正在使用Active Model序列化器。

我正在尝试访问在@current_user内部定义的ApplicationController,如下所示:

class ApplicationController < ActionController::API
  before_action :authenticate_request

  private
  def authenticate_request
    auth_header = request.headers['Authorization']
    regex = /^Bearer /
    auth_header = auth_header.gsub(regex, '') if auth_header
    begin
      @current_user = AccessToken.get_user_from_token(auth_header)
    rescue JWT::ExpiredSignature
      return render json: {error: "Token expired"}, status: 401
    end
    render json: { error: 'Not Authorized' }, status: 401 unless @current_user
  end
end

除了@current_user内部,我可以在任何地方使用ProjectSerializer,如下所示:

class V1::ProjectSerializer < ActiveModel::Serializer
  attributes(:id, :name, :key, :type, :category, :created_at)
  attribute :is_favorited
  belongs_to :user, key: :lead

  def is_favorited
    if object.favorited_by.where(user_id: @current_user.id).present?
      return true
    else
      return false
    end
  end

end

[ProjectSerializer位于我的app/项目树结构中:

app/
  serializers/
    v1/
      project_serializer.rb

我在尝试访问@current_user时遇到错误:

NoMethodError in V1::UsersController#get_current_user
undefined method `id' for nil:NilClass 

当我从UserController调用函数,然后转到UserSerializer,然后该串行器具有has_many :projects字段,该函数调用ProjectSerializer时,会发生这种情况。

ruby-on-rails ruby active-model-serializers rails-api
1个回答
0
投票

您可以使用instance_options访问变量。我相信您可以在项目控制器中访问@current_user。例如:

def projects
  @projects = Project.all
  render_json: @projects, serializer: ProjectSerializer, current_user: @current_user
end

在序列化器内部,您可以像明智地访问current_user:

 def is_favorited
    if object.favorited_by.where(user_id: @instance_options[:current_user].id).present?
      return true
    else
      return false
    end
  end
© www.soinside.com 2019 - 2024. All rights reserved.