我正在使用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
时,会发生这种情况。
您可以使用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