在ActiveModel :: Serializer

时间:2017-06-14 10:55:35

标签: ruby-on-rails serialization active-model-serializers

我使用active_model_serializers 0.10的api-only rails应用程序。我的current_user中有一个ApplicationController属性,我尝试从序列化程序中访问它以限制显示的数据。我可以通过像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:

当我尝试从Serializer中访问current_user时,出现以下错误:

*** NameError Exception: undefined local variable or method `current_user' for #<ExerciseSerializer:0x007ff15cd2e9c0>

显然范围是nil

任何想法都会有所帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

在无数次阅读官方文档失败后随机找到它:https://www.driftingruby.com/episodes/rails-api-active-model-serializer

所以这是有趣的部分:

def current_user_is_owner
  scope == object
end

所以current_user默认保存在scope变量 中,您不需要在控制器中添加代码来检索它。

在0.10中工作,自0.08起可用: https://github.com/rails-api/active_model_serializers/search?utf8=%E2%9C%93&q=scope&type=