使用active_model_serializers序列化权限(例如CanCan) [英] Serialize permissions (e.g. CanCan) with active_model_serializers

查看:84
本文介绍了使用active_model_serializers序列化权限(例如CanCan)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用active_model_serializers序列化权限?我无法访问模型和序列化程序中的 current_user 可以吗?方法。

How do I serialize permissions with active_model_serializers? I don't have access to current_user or the can? method in models and serializers.

推荐答案

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

First, to get access to the current_user in the serializer context, use the new scope feature:

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

如果您要手动实例化序列化程序,请确保通过范围:

In case you are instantiating serializers manually, be sure to pass the scope:

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

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

Then inside the serializer, add custom methods to add your own authorization pseudo-attributes, using scope (the current user) to determine permissions.

如果使用的是CanCan,则可以实例化Ability类以访问 can?方法:

If you are using CanCan, you can instantiate your Ability class to access the 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

这篇关于使用active_model_serializers序列化权限(例如CanCan)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆