Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 - view changes using Audited gem

In my app that I build to learn RoR, I want to add change tracking and use the Audited gem for that. While it is clear how to add it to my models, how can I see the changes?

I would want to add a link / button on each page for the different objects / classes / models that opens a view with the audit log. i.e. listing all changes (date/time, field, old value, new value, by user) sorted by the date/time of the change.

Can't find any documentation for it. All help to get started appreciated.

like image 501
Dimitri de Ruiter Avatar asked Feb 06 '23 23:02

Dimitri de Ruiter


2 Answers

I was needed exact feature when I was working with Papertrail Gem few months back. I modified my code to work for audited gem. I hope below haml code will give you really nice start.

%table.table.table-hover
  %thead
    %tr
      %th Type
      %th When
      %th Who
      %th What Changed
    - model.audits.order(:created_at).each do |audit|
      %tr
        %td= audit.action
        %td= audit.created_at
        %td= audit.user.name
        %td
          - audit.audited_changes.each do |k, v|
            %b= k.titleize
            from
            %b= "'#{v[0]}'"
            to
            %b= "'#{v[1]}'"
            %br

The code is self explanatory If you go through https://github.com/collectiveidea/audited

Explanation for audited_changes: For audited_changes we have hash like audit.audited_changes # => {"name"=>["Steve", "Ryan"]}. That means you have hash with string as a key and array with two values. first value is before updation and second is after updation.

like image 79
dnsh Avatar answered Feb 08 '23 23:02

dnsh


Thanks to @dnsh, i changed his code and added else:

%table.table.table-hover
  %thead
    %tr
      %th Type
      %th When
      %th Who
      %th What Changed
    - model.audits.order(:created_at).each do |audit|
      %tr
        %td= audit.action
        %td= audit.created_at
        %td= audit.user.name
        %td
          - audit.audited_changes.each do |k, v|
            %b= k.titleize
            - if v.class == Array # if updated
              from
              %b= "'#{v[0]}'"
              to
              %b= "'#{v[1]}'"
              %br
            - else # if created
              = v
like image 40
dumP Avatar answered Feb 09 '23 00:02

dumP