Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the original value of an attribute of a model using the gem PaperTrail?

I have a model that is tracked using PaperTrail.

I would like to compare the current value of the attribute 'name' to the value when it was first created. I can get the current value easily. How do I get its original value?

To get its current value: widget.name

To get its original value: widget.versions.first.???.name

I know that widget.versions.first.changeset will return a hash as follows.

{
    name: [nil, 'original name']
}

Although, I do not want to parse it; there must be a better way to obtain the original value.

like image 287
Ruslan Avatar asked Oct 28 '25 08:10

Ruslan


1 Answers

Use reify on the second version or return the widget if not present.

There's a closed issue about reify returning nil on the Github repo. It got ignored over there but I think this is a very valid issue and a common use-case.

Doing widget.versions.first.reify returns nil so the best way I could find is this:

widget.versions.second.reify

But that doesn't work when the object doesn't have any changes. So you need a nil check in there:

widget.versions.second&.reify || widget

This looks for the second version and if it's present will call reify, which returns the original object. If it's not present it will simply return the widget itself.

If you want to be clean about it, you can add this as a method to the class:

# Returns the original version of this object or just this object if there has been no changes.
def original_version
  self.versions.second&.reify || self
end

I have an open Issue/Feature Request with PaperTrail to add original_version to the core library itself:

https://github.com/paper-trail-gem/paper_trail/issues/1204

Give it an upvote if you want it in there.

like image 89
Joshua Pinter Avatar answered Oct 30 '25 23:10

Joshua Pinter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!