Serialize permissions (e.g. CanCan) using active_model_serializers

How to serialize permissions using active_model_serializers? I do not have access to the current_user or can? method can? in models and serializers.

+8
ruby-on-rails cancan activemodel active-model-serializers
source share
3 answers

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 
+22
source share

We created a stone that provides this functionality: https://github.com/GroupTalent/active_model_serializers-cancan

+2
source share

I think you can pass whatever you want with serialization_scope so that I just pass the ability.

 class ApplicationController < ActionController::Base ... serialization_scope :current_ability def current_ability @current_ability ||= Ability.new(current_user) end end class CommentSerializer < ActiveModel::Serializer attributes :id, :content, :created_at, :can_update def can_update scope.can?(:update, object) end end 

I cannot do otherwise, as my abilities are based on two variables (not in the example above).
If you still need access to current_user, you can simply set the instance variable in Ability.

+2
source share

All Articles