First, to access current_user in the context of a serializer, use the new scope function:
class ApplicationController < ActionController::Base ... serialization_scope :current_user end
If you run serializers manually, be sure to pass the scope:
model.active_model_serializer.new(model, scope: serialization_scope)
Then, inside the serializer, add your own methods to add your authorization pseudo-attributes, using scope (current user) to determine permissions.
If you use CanCan, you can create an instance of the Ability class to access the can? :
attributes :can_update, :can_delete def can_update # `scope` is current_user Ability.new(scope).can?(:update, object) end def can_delete Ability.new(scope).can?(:delete, object) end
Jo liss
source share