ruby-on-rails - 如何拒绝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 我会将它发送到序列化程序的参数中,并且可以根据它们的角色删除属性。
解决方案
您可以通过传入 Proc 来使用 FastJSONAPI 的条件属性。我不是很清楚你的代码是如何实现角色的,但是让我们假设你有一个admin
角色并且你想在用户是管理员时显示电话。下面的代码应该适用于该用例:
class CustomerSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :email, :phone
attribute :phone, if: Proc.new { |record| record.admin? }
end
推荐阅读
- python - selenium 可以在 Outlook Online 中找到_element_by_xpath 吗?
- c# - 扩展 AuditedAttribute 以替换或屏蔽审计值
- javascript - 完整日历描述中的新行
- c# - Mailkit MimeKit.MimeMessage 错误:未知的初始化参数:System.Byte []
- php - 匹配正则表达式
- javascript - 在可重用的 Razor 类库中包含静态文件
- c# - ASP.NET API 和 nodejs 网站的 Windows 身份验证
- javascript - 使用显示块单击按钮时未显示 HTML 表格
- actionscript-3 - 获取点和影片剪辑之间的距离
- c++ - 如何在 MFC Dialog 应用程序中插入更多对话框?