使用active_model_serializers序列化权限(例如CanCan)
如何使用active_model_serializers序列化权限? 我没有访问current_user
或can?
模型和序列化器中的方法。
首先,要访问序列化程序上下文中的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上设置实例变量即可。
- 如何在active_model_serializers中执行预先加载
- 控制器中的索引方法不适用于活动模型序列化程序
- 在Rails中使用ActiveModel :: Serializer – JSON数据在json和index响应之间有所不同
- ActiveModel :: Serializers Gem – Versioned API命名空间问题
- 使用ActiveModel :: Serializer序列化具有属性的数组/关系
- 使用active_model_serializers实现API版本控制的正确方法
- 如何使用active_model_serializers为嵌套对象选择序列化程序
- 强制活动模型序列化程序返回关联
- 更改活动模型序列化器默认适配器