【发布时间】:2017-11-16 11:44:02
【问题描述】:
我有一个使用 active_model_serializers 0.10 的仅 api rails 应用程序。我的ApplicationController 中有一个current_user 属性,我试图从我的序列化程序中访问它以限制显示的数据。我可以通过像ExerciseSerializer.new(@exercise, scope: current_user) 那样手动将其传递给范围来做到这一点,但希望有一个通用的解决方案。
这是我的ApplicationController:
class ApplicationController < ActionController::API
include Response
include ExceptionHandler
serialization_scope :view_context
# called before every action on controllers
before_action :authorize_request
attr_reader :current_user
def check_access_rights(id)
@current_user.id == id
end
def check_admin_rights
if !@current_user.admin
raise(ExceptionHandler::AuthenticationError, Message.unauthorized)
end
end
private
# Check for valid request token and return user
def authorize_request
@current_user = (AuthorizeApiRequest.new(request.headers).call)[:user]
end
end
这是我的序列化程序之一:
class ExerciseSerializer < ActiveModel::Serializer
attributes :id, :name, :description, :image_url, :note
delegate :current_user, :to => :scope
has_many :exercise_details
end
这就是我展示对象的方式:
def json_response(object, status = :ok)
render json: object, status: status
end
序列化时出现以下错误:
** Module::DelegationError Exception: ExerciseSerializer#current_user delegated to scope.current_user, but scope is nil:
当我尝试从序列化程序中访问current_user 时,我收到以下错误:
*** NameError Exception: undefined local variable or method `current_user' for #<ExerciseSerializer:0x007ff15cd2e9c0>
显然范围是nil。
任何想法都会有所帮助。谢谢!
【问题讨论】:
标签: ruby-on-rails serialization active-model-serializers