Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit a paper_trail version without creating a new version

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?

like image 948
map7 Avatar asked Sep 28 '22 06:09

map7


1 Answers

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.

like image 185
Jared Beck Avatar answered Dec 27 '22 09:12

Jared Beck