首页 > 解决方案 > 如何拒绝fastjson_api中的属性?

问题描述

我开始使用 fastjson_api,我已经在我的项目中实现了基于属性的控制,当我返回 JSON 数据时如何拒绝属性。
例如:-
我有一个客户表,其中包含客户姓名、电子邮件、电话、地址对于某些角色,我可能会授予对电话号码的访问权限,而对于某些角色,我不会授予他们访问权限
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 响应中动态过滤掉属性。
对于角色 1 not_allowed_attributes = ["email","phone"]
对于角色 2 not_allowed_attributes = ["phone"]

not_allowed_attributes 我会将它发送到序列化程序的参数中,并且可以根据它们的角色删除属性。

标签: ruby-on-railsrubyfastjsonapi

解决方案


您可以通过传入 Proc 来使用 FastJSONAPI 的条件属性。我不是很清楚你的代码是如何实现角色的,但是让我们假设你有一个admin角色并且你想在用户是管理员时显示电话。下面的代码应该适用于该用例:

class CustomerSerializer
  include FastJsonapi::ObjectSerializer
  attributes :name, :email, :phone  
  attribute :phone, if: Proc.new { |record| record.admin? }
end

推荐阅读