我开始使用fastjson_api,我已经在我的项目中实现了基于属性的控制,当我返回JSON数据时,如何拒绝属性。
例如:
我有一个customer表,其中有一些角色的客户名称、电子邮件、电话、地址,我可能会提供电话号码的访问权限,而对于某些角色,我不会授予他们访问权限
not_allowed_attributes = ["phone"]
class CustomerSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :email, :phone
attribute :phone do |object|
unless not_allowed_attributes.include?"phone"
object.phone
end
end
end但是它不是一种动态的实现方式,所以每当not_allowed_attributes中发生变化时,它都应该动态地从JSON响应中过滤掉属性。
对于role1 not_allowed_attributes =“电子邮件”,“电话”
对于电话not_allowed_attributes =“role2”
not_allowed_attributes,我会在序列化程序的参数中发送它,并且可以根据属性的角色删除它们。
发布于 2019-11-18 16:07:14
您可以通过传入一个conditional attributes来使用FastJSONAPI的Proc。我不太清楚您的代码是如何实现角色的,但让我们假设您有一个admin角色,并且希望在用户是管理员时显示电话。下面的代码应该适用于该用例:
class CustomerSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :email, :phone
attribute :phone, if: Proc.new { |record| record.admin? }
endhttps://stackoverflow.com/questions/58908858
复制相似问题