ruby-on-rails - Rails:使用 json 类型查询审计
问题描述
我在我的应用程序中使用经过审核的 gem和 PostgreSQL 数据库,我希望能够查询:audited_changes
所有条目的属性,并在:program_status
. 更改本身无关紧要,我希望所有涉及:program_status
.
审计示例:
#<Audit:0x007ff31789de80
id: 11283,
auditable_id: 2225,
auditable_type: "Client",
associated_id: nil,
associated_type: nil,
user_id: nil,
user_type: nil,
username: nil,
action: "update",
audited_changes: {"program_status"=>["full maintenance", "active"]},
version: 21,
comment: nil,
remote_address: "::1",
request_uuid: "a5a6a9f0-302a-443b-b09a-fd466557f757",
created_at: Thu, 12 Jul 2018 17:49:40 EDT -04:00>
#<Audit:0x007ff31789de80
id: 11284,
auditable_id: 2226,
auditable_type: "Client",
associated_id: nil,
associated_type: nil,
user_id: nil,
user_type: nil,
username: nil,
action: "update",
audited_changes: {"program_status"=>["inactive", "active"]},
version: 21,
comment: nil,
remote_address: "::1",
request_uuid: "a5a6a9f0-302a-443b-b09a-fd466557f757",
created_at: Thu, 12 Jul 2018 17:49:40 EDT -04:00>
#<Audit:0x007ff31789de80
id: 11284,
auditable_id: 2226,
auditable_type: "Client",
associated_id: nil,
associated_type: nil,
user_id: nil,
user_type: nil,
username: nil,
action: "update",
audited_changes: {"program_status"=>["full_maintenance", "limited_maintenance"]},
version: 21,
comment: nil,
remote_address: "::1",
request_uuid: "a5a6a9f0-302a-443b-b09a-fd466557f757",
created_at: Thu, 12 Jul 2018 17:49:40 EDT -04:00>
似乎我需要使用 的变体['{"a": {"b":"foo"}}'::json->'a'][2]
,我只是不确定如何在 rails 中使用它。
解决方案
你用的是什么数据库?如果您使用的是 MySQL,则数据库字段实际上是一个序列化的文本列,因此您可以使用类似
.where('audited_changes LIKE "%program_status%"')
如果你使用 Mongo,比如
.where(audited_changes: {program_status: '$exists'})
如果您使用 PostreSQL,我认为它支持 json 数据类型,我猜它有一些特定的语法来查询这些字段。
编辑:对于 postgres
.where('audited_changes ? array[:keys]', keys: ['program_status'])
(如果您需要多个键https://www.postgresql.org/docs/9.4/static/functions-json.html ,请查看表 9-41 中的 OR 和 AND 操作)
推荐阅读
- python - 使用 Python API 客户端从 PostgreSQL 数据库更新 Zendesk 票证
- thorntail - Thorntail 微剖面依赖
- angular - 使用带有“gap”的“row wrap”时如何处理角度弹性布局中每行的最后一个元素
- c# - 静态内容 - 名称空间中不存在名称“资源”。无效标记
- docusignapi - 是否可以有条件地显示 DocuSign 模板部分/部分?
- android - Android - 样式不适用于对话框片段
- reactjs - 单击按钮时获取数组内的输入值
- python - python代码不适用于excel但适用于csv文件
- javascript - 图像对象适合的格式问题以及如何在行中添加按钮
- tcl - 在TCL中,当文件处于连续写操作时,是否可以删除文件的前几行或前n行