2017-06-14 55 views
1

我有一個使用active_model_serializers 0.10的api-only rails應用程序。我在我的ApplicationController中有current_user屬性,並試圖從我的序列化程序訪問它以限制顯示的數據。我可以通過將其作爲手動範圍來傳遞,如ExerciseSerializer.new(@exercise, scope: current_user),但希望有一個通用的解決方案。在ActiveModel :: Serializer中包含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 [email protected]_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

任何想法都會有所幫助。謝謝!

回答

相關問題