'Problems implementing Paper_trail Ruby gem and displaying changes to records in ActiveRecord
I was following the really helpful post/video on how to instal and use Paper_trail gem to nicely display any changes made to a record in my database. https://www.driftingruby.com/episodes/auditing-with-paper-trail I want to do exactly the same as in the video!
However, it isn't printing the changes and instead, I get the error as shown in the screenshot attached.
I assume it is something to do with the method as written in paper_trail.rb file but I have no idea how to fix this.
The repository is available here - https://github.com/PoppyJennings/contacts-list-app
paper_trail.rb
PaperTrail.config.track_associations = false
PaperTrail.config.version_limit = 5
PaperTrail.serializer = PaperTrail::Serializers::JSON
PaperTrail::Version.class_eval do
def changed_object
@changed_object ||= JSON.parse(self.object, object_class: OpenStruct)
end
end
show.html.erb (highlighting line with error)
<h2>Versions</h2>
<table class='table'>
<thead>
<tr>
<th>ID</th>
<th>Modifier</th>
<th>Action</th>
<th>Changes</th>
</tr>
</thead>
<tbody>
<% @contact.versions.each do |version| %>
<%= tag.tr do %>
<%= tag.td version.id %>
<%= tag.td version.whodunnit %>
<%= tag.td link_to 'rollback', contact_rollback_path(@contact, version: version) %>
<%= tag.td do %>
<%= tag.ul class: 'list-group' do %>
<li class='list-group-item'>
<strong>First Name:</strong>
*****<%= version.changed_object.first_name %>*****
</li>
<li class='list-group-item'>
<strong>Last Name:</strong>
<%= version.changed_object.last_name %>
</li>
<li class='list-group-item'>
<strong>Email:</strong>
<%= version.changed_object.email %>
</li>
<li class='list-group-item'>
<strong>Phone:</strong>
<%= version.changed_object.phone %>
</li>
<% end %>
<% end %>
<% end %>
<% end %>
</table>
Really appreciate any help on this as no idea where to go with it!
Solution 1:[1]
changed_object is not an official PT method. It would be better to follow the official install instructions before attempting to hack the library. (Nothing wrong with hacking, but walk before you run)
There are many ways you can achieve your goals using official methods. For example, in your ERB, instead of
@contact.versions.each do |version|
version.changed_object.first_name
you could use
@contact.versions.each do |version|
contact_from_version = version.reify
contact_from_version.first_name
Or, you could install PT --with-changes, which would enable a more performant ERB implementation, via the resulting object_changes column and/or PaperTrail::VersionConcern#changeset.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jared Beck |
