Not able to access the current_user from a serializer class

class QuestionSerializer < ActiveModel::Serializer
  attributes :id,:body,:votes,:liked
  def body
    object.body
  end
  
  def liked
    if current_user.liked? object 
      true
    else
      false
    end
  end
  
  def votes
    object.votes.up.count
  end
end

I have this method in the ApplicationController.

 def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user

That could not happen because QuestionSerializer didnt inherit from ApplicationController. What I did was then in Question model class defined this method which had access to the current_user.

def liked?
   if self.liked_by? current_user
     true
   else
     false
   end
 end

But this doesnt work either

You might be looking for the scope method1

I haven’t tested this, but it looks like your original implementation could be written as

class QuestionSerializer < ActiveModel::Serializer
...
  def liked
    scope.liked? object
  end
end

Thanks for the answer. But scope is set to the current_user only if do render :json. I was actually calling this

 serializer = QuestionSerializer.new @question 

in the controller action. So I had to define a method in Question model class and then called it from the Serializer class.