Find version where specific attribute has changed in papertrail
Asked Answered
B

5

14

I'm using the Papertrail gem in my project and have searched extensively to try and find how to do the following.

What I'd like to do is find the version of my object where a specific attribute came to be a specific value i.e.

object.versions.where(attribute: "value")

Does anyone know if this is even possible with Papertrail?

Bryner answered 11/6, 2014 at 11:13 Comment(0)
H
1

As of PaperTrail 12.1 you can do

object.versions.where_object_changes_to(attribute: "value")
Humanitarianism answered 22/4, 2022 at 12:49 Comment(0)
B
11

The following gets all the versions where attribute became value (which in most apps is probably around 1):

object.versions.
       map(&:object_changes).
       map{|a| YAML::load a}.
       select{|a| (a[:attribute] || [])[1]=='value'}

Result would be something like:

[{"attribute"=>[nil, "value"],
  "updated_at"=>[2015-01-02 12:20:36 UTC, 2015-01-02 12:20:56 UTC]}]

The updated_at[1] value indicates when attribute became value.

Getting the id of the Version can be built upon the provided code snippet.

Blitzkrieg answered 2/1, 2015 at 17:51 Comment(1)
Thanks, this does answer my original question. Though for speed of processing (i.e. database queries etc.) my original approach remains my favoured one.Bryner
B
6

Well, I've concluded this is not possible out-of-the-box in paper_trail.

What I ended up doing was, when one of the specific attributes was updated, save a flag in a separate metadata column in the Versions table.

Then I can search against these columns in the future to find out when that specific attribute changed.

Hopefully this helps someone else.

Bryner answered 13/6, 2014 at 8:28 Comment(0)
R
6

Here's another option for those who don't want to use a separate metadata column:

def version_where_attribute_changed_to(attribute_name, attribute_value)
  versions.select do |version|
    object_changes = YAML.load version.object_changes
    (object_changes[attribute_name.to_s] || [])[1] == attribute_value
  end
end
Reathareave answered 29/1, 2018 at 13:20 Comment(0)
H
1

As of PaperTrail 12.1 you can do

object.versions.where_object_changes_to(attribute: "value")
Humanitarianism answered 22/4, 2022 at 12:49 Comment(0)
R
0

If you are looking for versions where a specified attribute changed to or from any value, you can use the below:

@object.versions
  .map(&:changeset)
  .select{|a| a["attribute"].present?}
Rondeau answered 30/7, 2023 at 4:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.