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

2023-11-24

如何使用 active_model_serializers 序列化权限?我无权访问current_user or the can?模型和序列化器中的方法。


首先,要访问current_user在序列化器上下文中,使用新的范围功能:

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

如果您手动实例化序列化器,请务必传递范围:

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

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

如果您使用 CanCan,您可以实例化您的 Skill 类来访问can? method:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 active_model_serializers 序列化权限(例如 CanCan) 的相关文章

随机推荐