Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include current_user in ActiveModel::Serializer

I have an api-only rails application using active_model_serializers 0.10. I have a current_user attribute in my ApplicationController and am trying to access it from my serializers in order to restrict the data shown. I can do it by passing it to scope manually like this ExerciseSerializer.new(@exercise, scope: current_user), but would like to have a general solution.

This is my 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

This is one of my serializers:

class ExerciseSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :image_url, :note
  delegate :current_user, :to => :scope
  has_many :exercise_details

end

And this is how I present the objects:

  def json_response(object, status = :ok)
    render json: object, status: status
  end

When serializing I get the following error:

** Module::DelegationError Exception: ExerciseSerializer#current_user delegated to scope.current_user, but scope is nil:

When I try accessing the current_user from within the Serializer, I get the following error:

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

And obviously scope is nil.

Any ideas would be helpful. Thanks!

like image 447
smeshko Avatar asked Sep 18 '25 15:09

smeshko


1 Answers

Found it randomly after countless times unsuccessfully reading the offical docs : https://www.driftingruby.com/episodes/rails-api-active-model-serializer

So here is the interesting part:

def current_user_is_owner
  scope == object
end

So current_user is saved in the scope variable by default, you don't need to add code in the controller to retrieve it.

Works in 0.10 and available since 0.08: https://github.com/rails-api/active_model_serializers/search?utf8=%E2%9C%93&q=scope&type=

like image 68
abdourakhmane Avatar answered Sep 20 '25 06:09

abdourakhmane