1

I am using the audited gem for tracking changes to a record. An audit object looks like

  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>,

and so on. Now i want to filter out only those audits where audit.audited_changes which is a hash in the audited object includes a change in first name. How can i query this one?

Pallavi Hegde
  • 219
  • 2
  • 15

1 Answers1

2

If you are using PostgreSQL and this audited_changes can be set as json type then query can be fire as

Audited::Audit.where("(audited_changes->'first_name') is not null AND auditable_type = ?", "Consumer") # for all the records of type Consumer

or for a particular object Audited::Audit.where("(audited_changes->'first_name') is not null AND auditable_type = ? AND auditable_id = ?", "Consumer", "#{consumer_id}") # for all the records of type Consumer

Because whenever audit object gets created audited_changes has only those key that you changed while creating/updating.

Kiran Kumawat
  • 82
  • 1
  • 10
  • hey, this doesn't seem to be working. it's just returning an active record relation.. i am using postgress – Pallavi Hegde Apr 14 '17 at 07:08
  • Have you changed column type to json becuase it is working for me http://stackoverflow.com/questions/23911740/get-records-where-json-column-key-is-null – Kiran Kumawat Apr 14 '17 at 09:25
  • Where audited_change is using the older String YAML datatype, this will work: .where("audited_changes LIKE '%first_name:%'") – Rabi Jan 25 '21 at 12:13