使用active_model_serializers序列化权限(例如CanCan)

如何使用active_model_serializers序列化权限? 我没有访问current_usercan? 模型和序列化器中的方法。

首先,要访问序列化程序上下文中的current_user ,请使用新的作用域function:

 class ApplicationController < ActionController::Base ... serialization_scope :current_user end 

如果您手动实例化序列化程序,请务必通过范围:

 model.active_model_serializer.new(model, scope: serialization_scope) 

然后在序列化程序内部添加自定义方法以添加自己的授权伪属性,使用scope (当前用户)来确定权限。

如果您正在使用CanCan,您可以实例化您的Ability类来访问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 

我们创建了一个提供此function的gem: https : //github.com/GroupTalent/active_model_serializers-cancan

我认为你可以将任何你想要的东西传递给serialization_scope所以我只是通过了能力。

 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 

我不能这样做,因为我的能力实际上是基于两个变量(不在上面的例子中)。
如果您仍然需要访问current_user,则只需在Ability上设置实例变量即可。