airblade/paper_trail — Issue #121: Restore has_many through association when undoing a destroy
Author: elle
Created: 2012-01-11 01:36:45+00:00
State: open

This is based on Ryan Bates' railcast and I am only trying to restore deleted join records.
I am manually defining which children I would like to restore as a meta column on versions, like so:

```ruby
class Team < ActiveRecord::Base
has_paper_trail :meta => { :children => ['team_members'] }
has_many :team_members, :dependent => :destroy
end
```

```ruby
class Version < ActiveRecord::Base
attr_accessible :children
serialize :children, Array

after_save :restore_children

def recreating_item?
if item
item.versions[-1].try(:event) == 'create' && item.versions[-2].try(:event) == 'destroy'
end
end

def restore_children
if children && recreating_item?
children.each do |model_name|
records = Version.where(:item_type => model_name.classify)

records.each do |ver|
ver.reify.save! if ver.event == 'destroy' && ver.created_at > 20.seconds.ago
end
end
end
end
end
```

I could be checking if the child model responds_to? :versions but since I manually define which models I would like to go through, I didn't think it was necessary.

One problem is that I am only looking 20.seconds.ago for recent records. But that option will only occur when people click on the 'undo destroy' link.

Anyhow, this works for me.