How to track custom events in paper_trail?
Asked Answered
C

3

8

I am using paper_trail for audit trail. Along with create, update and delete events I want to track few custom events like view(record), sent(email) etc. How can we introduce such custom events while auditing a model?

Canute answered 24/3, 2012 at 12:34 Comment(0)
C
4

I have found a tweak to add custom events in paper_trail managed Versions:

Version.create(item_type: "Campaign", item_id: campaign.id, event: "Sent")

Maybe this is not right solution, but it helped me to achieve the goal. I would like to explore paper_trail more to find a better solution.

Canute answered 26/3, 2012 at 5:33 Comment(0)
E
3

Following the paper trail flow, and having paper trail hooked to your touch events:

record.paper_trail_event = 'notified'
record.touch

If you don't want to have that hook in place you can:

record.versions.create!(event: 'notified')

The main problem with the second approach is that it won't apply any of the PaperTrail scoped params, nor any other dynamic field you may have defined for that model PaperTrail config.

You will need to set those manually. For the request.whodunnit it would be like:

record.versions.create!(event: 'notified', whodunnit: current_user.id)
Eudemonics answered 28/11, 2020 at 14:33 Comment(1)
record.paper_trail_event doesn't work for some reason, however the later 2 does, which is quite hacky. Is there any way to also add the global columns set by info_for_paper_trail without having to do all these manually?Baribaric
W
1

See simple hit counter for page views in rails as an answer to the first part of your question. As for tracking sent mails, you may want to use Observer pattern.

In any case all these events are outside of paper_trail domain. While paper_trail simply creates versions of your model during data changing, what you need is to observe custom event and write to DB all necessary information about that event.

Wenwenceslaus answered 24/3, 2012 at 14:3 Comment(1)
thanks @nash-bridges, your answer is very useful. I am preparing a prototype application which requires auditing of basic events like create, update, delete as well as some custom events as I mentioned earlier. As paper_clip has nice support of these basic events tracking, I was looking some tweak so I can track custom actions along with basic ones. This arrangement is for time being till I demonstrate the POC to client.Canute

© 2022 - 2024 — McMap. All rights reserved.