如何使用 active_model_serializers 序列化权限?我无权访问 current_user
或 can?
模型和序列化器中的方法。
最佳答案
首先,访问 current_user
在序列化程序上下文中,使用新的范围功能:
class ApplicationController < ActionController::Base
...
serialization_scope :current_user
end
如果您手动实例化序列化程序,请确保传递范围:
model.active_model_serializer.new(model, scope: serialization_scope)
然后在序列化程序中,使用
scope
添加自定义方法以添加您自己的授权伪属性。 (当前用户)来确定权限。如果你使用 CanCan,你可以实例化你的能力类来访问
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
关于ruby-on-rails - 使用 active_model_serializers 序列化权限(例如 CanCan),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11660179/