Jo *_*iss 10 ruby-on-rails activemodel cancan active-model-serializers
如何使用active_model_serializers序列化权限?我无法访问模型和序列化程序中current_user
的can?
方法或方法.
Jo *_*iss 22
首先,要访问current_user
序列化程序上下文,请使用新的作用域功能:
class ApplicationController < ActionController::Base
...
serialization_scope :current_user
end
Run Code Online (Sandbox Code Playgroud)
如果您手动实例化序列化程序,请务必通过范围:
model.active_model_serializer.new(model, scope: serialization_scope)
Run Code Online (Sandbox Code Playgroud)
然后在序列化程序内部添加自定义方法以添加您自己的授权伪属性,使用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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3663 次 |
最近记录: |