Skip to content

Commit

Permalink
Added some documentation and has_many option
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeremy Anderson committed Jan 14, 2021
1 parent 1ea31db commit 49a9722
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,17 @@ t.amount # 100
t.location.latitude # 12.345, instead of 54.321
```

When calling `changeset` on a `version` you can include changes to associations by specifying the following options

- To restore Has-Many associations, use option `has_many: true`
- To restore Has-Many-Through associations, use option `has_many_through: true`

For example:

```ruby
item.versions.last.changeset(has_many: false, has_many_through: true)
```

# Limitations

1. Only reifies the first level of associations. If you want to include nested associations simply add `:through` relationships to your model.
Expand Down
15 changes: 14 additions & 1 deletion lib/paper_trail_association_tracking/version_concern.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,30 @@ def changeset(options = {})
super()
return @changeset unless ::PaperTrail.config.track_associations?

@changeset = load_changeset_has_many(@changeset) if options[:has_many]
@changeset = load_changeset_has_many_through(@changeset) if options[:has_many_through]
@changeset
end

private

def load_changeset_has_many(changes)
has_many_assocs
.reduce(changes) do |acc, assoc|
assoc_changes = has_many_changes(assoc)
acc.merge!(assoc_changes) if assoc_changes.any?

acc
end

changes
end

def load_changeset_has_many_through(changes)
has_many_through_assocs
.reduce(changes) do |acc, assoc|
assoc_changes = has_many_through_changes(assoc)
return acc.merge(assoc_changes) if assoc_changes.any?
acc.merge!(assoc_changes) if assoc_changes.any?

acc
end
Expand Down

0 comments on commit 49a9722

Please sign in to comment.