From 4ad6254b742c535a133687d03ec74abbf44b6a1f Mon Sep 17 00:00:00 2001 From: Sam Boylett Date: Wed, 18 May 2016 12:15:28 +0100 Subject: [PATCH] Fix for HABTM associations when updated within 1 transaction When updating 2 models with a HABTM association, and using accepts_nested_attributes_for, the association was using the version ID instead of the transaction ID to reference the change. This was braking the association logic and preventing proper reification. --- CHANGELOG.md | 2 ++ lib/paper_trail/has_paper_trail.rb | 2 +- test/dummy/app/models/foo_habtm.rb | 1 + test/unit/associations_test.rb | 24 ++++++++++++++++++++++++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a3a5007..3b6f0af3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ ### Fixed +- [#812](https://github.com/airblade/paper_trail/pull/812) - + Issue with saving HABTM associated objects using accepts_nested_attributes_for - Improvements to documentation ## 5.0.1 (2016-05-04) diff --git a/lib/paper_trail/has_paper_trail.rb b/lib/paper_trail/has_paper_trail.rb index d38e5814..31bb793f 100644 --- a/lib/paper_trail/has_paper_trail.rb +++ b/lib/paper_trail/has_paper_trail.rb @@ -535,7 +535,7 @@ module PaperTrail self.class.paper_trail_save_join_tables.include?(a.name) || a.klass.paper_trail_enabled_for_model? assoc_version_args = { - version_id: version.id, + version_id: version.transaction_id, foreign_key_name: a.name } assoc_ids = diff --git a/test/dummy/app/models/foo_habtm.rb b/test/dummy/app/models/foo_habtm.rb index 6ce32790..8f97d405 100644 --- a/test/dummy/app/models/foo_habtm.rb +++ b/test/dummy/app/models/foo_habtm.rb @@ -1,4 +1,5 @@ class FooHabtm < ActiveRecord::Base has_and_belongs_to_many :bar_habtms + accepts_nested_attributes_for :bar_habtms has_paper_trail end diff --git a/test/unit/associations_test.rb b/test/unit/associations_test.rb index a3769a8c..ed3f8421 100644 --- a/test/unit/associations_test.rb +++ b/test/unit/associations_test.rb @@ -988,5 +988,29 @@ class AssociationsTest < ActiveSupport::TestCase end end end + + context "updated via nested attributes" do + setup do + @foo = FooHabtm.create( + name: "foo", + bar_habtms_attributes: [{ name: "bar" }] + ) + Timecop.travel 1.second.since + @foo.update_attributes( + name: "foo2", + bar_habtms_attributes: [{ id: @foo.bar_habtms.first.id, name: "bar2" }] + ) + + @reified = @foo.versions.last.reify(has_and_belongs_to_many: true) + end + + should "see the associated object as it was at the time" do + assert_equal "bar", @reified.bar_habtms.first.name + end + + should "not persist changes to the live object" do + assert_not_equal @reified.bar_habtms.first.name, @foo.reload.bar_habtms.first.name + end + end end end