westonganger / active_snapshot

Simplified snapshots and restoration for ActiveRecord models and associations with a transparent white-box implementation
MIT License
103 stars 16 forks source link

Restoring items not destroying records of the join table in a `has_many :through` association #11

Closed pjmartorell closed 2 years ago

pjmartorell commented 2 years ago

Hi, taking this code as an example:

class Assembly < ApplicationRecord
  has_many :manifests
  has_many :parts, through: :manifests
end

class Manifest < ApplicationRecord
  belongs_to :assembly
  belongs_to :part
end

class Part < ApplicationRecord
  has_many :manifests
  has_many :assemblies, through: :manifests
end

and having the following Assembly class:

class Assembly
  include ActiveSnapshot

  has_snapshot_children do
    instance = self.class.includes(:manifests).find(id)

    {
      manifests: instance.manifests
    }
  end
end

I noticed that, when restoring a snapshot, the Manifest records that were destroyed before the snapshot are re-created, that's okay. But the ones that were created after the snapshot are not destroyed. Do you know what can be the issue or if there is any workaround? I can give you a more detailed example but it will take a while for me to create a minimum working example.

westonganger commented 2 years ago

Here is the restore! method, should be pretty easy to debug it you want to take a stab at it

https://github.com/westonganger/active_snapshot/blob/be3616e7ff62e6caa37d6a3cab1e380b5e4885a9/lib/active_snapshot/models/snapshot.rb#L36-L76

pjmartorell commented 2 years ago

Thanks, I debugged the code you pointed out, specially this block:

if children_to_keep.exclude?(key)
  delete_method.call(child_record)
end

and I saw I got mistaken when restoring different snapshots. Thanks and sorry for the inconvenience.