使用rails audited gem根据审计的更改筛选出结果

时间:2017-04-14 05:32:16

标签: ruby-on-rails acts-as-audited

我使用审计的gem来跟踪记录的更改。审计对象看起来像

  id: 1,
  auditable_id: 1,
  auditable_type: "Customer",
  associated_id: nil,
  associated_type: nil,
  user_id: nil,
  user_type: nil,
  username: nil,
  action: "create",
  audited_changes:
    {"first_name"=>"Milan McClure",
     "last_name"=>"Wilfred Carter IV",
     "email"=>"brian.hahn@vonrueden.com",
     "sms_optin"=>true,
     "title"=>nil,
     "is_deleted"=>false,
     "deleted_at"=>nil,
     "restored_at"=>nil},
  version: 1,
  comment: nil,
  remote_address: nil,
  request_uuid: "6e462bf8-4788-4ec5-a6ee-f31a7a8226d0",
  created_at: Wed, 12 Apr 2017 12:20:39 UTC +00:00>,

等等。现在我想只筛选出审计对象中作为哈希值的audit.audited_changes包含名字更改的审计。我该如何查询这个?

1 个答案:

答案 0 :(得分:1)

如果您正在使用PostgreSQL,并且此audited_changes可以设置为json类型,那么查询可以是

Audited :: Audit.where(“(audited_changes->'first_name')不为null且auditable_type =?”,“Consumer”)#对于所有类型为Consumer的记录

或特定对象 审核:: Audit.where(“(audited_changes->'first_name')不为空且auditable_type =?AND auditable_id =?”,“Consumer”,“#{consumer_id}”)#for消费者

类型的所有记录

因为无论何时创建审计对象,audited_changes都只包含您在创建/更新时更改的那些键。