首页 > 解决方案 > 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 中使用它。

标签: ruby-on-railsactiverecord

解决方案


你用的是什么数据库?如果您使用的是 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 操作)


推荐阅读