Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use devise current_user in Active Model Serializers

I'm using Active Model Serializer 0.10.7 in rails5

and I wanna know how to access devise current_user in serializer.

current_user is supposed to be set for scope by default.

according to doc

https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/serializers.md#controller-authorization-context

but my code doesn't work well...

anybody knows about this?

class BookSerializer < ActiveModel::Serializer

  attributes :id, :title, :url, :image, :is_reviewed

  def is_reviewed
    object.reviews.pluck(:user_id).include?(current_user.id)
  end
end 

and Book controller look like this.

class BooksController < ApplicationController
  def index
    @books = Book.order(created_at: :desc).page(params[:page])
    respond_to do |format|
      format.html
      format.json {render json: @books, each_serializer: BookSerializer}
    end
  end
end
like image 741
Otani Shuzo Avatar asked Dec 14 '17 09:12

Otani Shuzo


4 Answers

Devise doesn't expose the current_user helper to models or serializers - you can pass the value to the model from the controller, or set it in a storage somewhere.

Some examples from other answers:

https://stackoverflow.com/a/3742981/385532

https://stackoverflow.com/a/5545264/385532

like image 152
Matt Avatar answered Sep 29 '22 15:09

Matt


It is possible to pass a scope into your serializer when instantiating it in the controller (or elsewhere for that matter). I appreciate that this is for individual objects and not arrays of objects:

BookSerializer.new(book, scope: current_user)

Then in your Book Serializer you can do:

class BookSerializer < ActiveModel::Serializer

  attributes :id, :title, :url, :image, :is_reviewed

  private

  def is_reviewed
    object.reviews.pluck(:user_id).include?(current_user.id)
  end

  def current_user
    scope
  end
end 


like image 35
L.Youl Avatar answered Sep 29 '22 16:09

L.Youl


in application controller:

class ApplicationController < ActionController::Base
  ...
  serialization_scope :view_context


end

in serializer:

class BookSerializer < ActiveModel::Serializer

  attributes :id, :title, :url, :image, :is_reviewed

  def is_reviewed
    user = scope.current_user
    ...
  end
end 
like image 22
Dima I. Belinski Avatar answered Sep 29 '22 15:09

Dima I. Belinski


If you are using active_model_serializers gem, then it is straight forward.

In your serializer just use the keyword scope.

Eg:-

class EventSerializer < ApplicationSerializer
  attributes(
    :id,
    :last_date,
    :total_participant,
    :participated
  )

  def participated
    object.participants.pluck(:user_id).include?(scope.id)
  end
end
like image 28
Tashi Dendup Avatar answered Sep 29 '22 15:09

Tashi Dendup