Edit a paper_trail version without creating a new version
Asked Answered
P

1

6

I'm using paper_trail 3.0.8 on a Rails 3.2 app and I've got a model called 'levels' and I keep versions of these levels. Each level has a from_date and a cost relating to it. Whenever someone changes the date a new version is created.

I allow people to remove old versions if they want and this works well. I would like the ability to modify an old paper_trail version and save it without creating a new version.

class Level < ActiveRecord::Base

  has_paper_trail :only => [:from_date],
    :if => Proc.new { |l|
      l.versions.count == 0 || l.versions.first.item != nil && (l.versions.first.item.from_date.nil? || l.from_date > l.versions.first.item.from_date)
    }

<snip code>
end

If I do the following it only updates the current level and not the version

level = Level.find 1
version=level.versions[1].reify
version.cost_cents = 1000
version.save

Is there anyway to update the cost_cents for an old version?

Also is there a way to update the from_date of an old version without creating a new version on the save?

Peipeiffer answered 23/7, 2015 at 4:0 Comment(0)
B
4

Is there anyway to update the cost_cents for an old version?

Yes, but the only way I know is a bit awkward.

PaperTrail::Version is a normal ActiveRecord object, so it's easy to work with in that sense, but the data is serialized (in YAML, by default) so you'll have to de-serialize, make your change, and re-serialize.

v = PaperTrail::Version.last
hash = YAML.load(v.object)
hash[:my_attribute] = "my new value"
v.object = YAML.dump(hash)
v.save

There may be a better way to do this with ActiveRecord's automatic-serialization features (like ActiveRecord::AttributeMethods::Serialization).

PS: I see you were trying to use reify, which returns an instance of your model, not an instance of PaperTrail::Version.

Brilliant answered 23/7, 2015 at 5:47 Comment(1)
This is the only solution that kinda works in 2020. Hash merging multiple attributes can create "duplicate values" for nested arrays or complex structures. This can cause some model verifications to fail. It's mind-boggling that there aren't any public API methods added to papertrail in last 5-6 years since it has been asked in several stackoverflow questions.Tome

© 2022 - 2024 — McMap. All rights reserved.