Track associated or child records with `has_snapshot_children`
masterTo ensure that child records (associations) are included in a snapshot, use the has_snapshot_children block in your model. The block is executed in the context of the instance (self).
Inside the block, you should:
- Reload the record from the database to ensure a clean state and eager load associations.
- Return a hash mapping association names to the records or specific configurations to be restored.
Supported configurations in the hash:
- Direct records: Mapping a key to an association (e.g.,
comments: instance.comments). - Nested associations: Mapping to an array of records (e.g.,
comment_sub_records: instance.comments.flat_map{|x| x.comment_sub_records }). - Custom record mapping: Providing a hash with
:records(e.g.,tags: { records: instance.tags }). - Custom deletion logic: Providing a hash with
:recordand a:delete_methodproc (e.g.,ip_address: { record: instance.ip_address, delete_method: ->(item){ item.release! } }).
class Post < ActiveRecord::Base
include ActiveSnapshot
has_snapshot_children do
# Reload to ensure clean state and eager loading
instance = self.class.includes(:tags, :ip_address, comments: [:comment_sub_records]).find(id)
{
comments: instance.comments,
comment_sub_records: instance.comments.flat_map{|x| x.comment_sub_records },
tags: {
records: instance.tags
},
ip_address: {
record: instance.ip_address,
delete_method: ->(item){ item.release! }
}
}
end
end