aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorArthur Neves <arthurnn@gmail.com>2016-10-28 17:15:23 -0400
committerArthur Neves <arthurnn@gmail.com>2016-10-28 17:15:23 -0400
commita0a37d9fd3c35f44fa58439fa41b4cdff2d25a98 (patch)
treeb0b66dc49790ea50f888784eb97a622f0854b14e
parentaaf561d26cf9a879ff40190b625155015c6225da (diff)
parent9991f14fced25dac3699b473a05cc7a196f9220e (diff)
downloadrails-a0a37d9fd3c35f44fa58439fa41b4cdff2d25a98.tar.gz
rails-a0a37d9fd3c35f44fa58439fa41b4cdff2d25a98.tar.bz2
rails-a0a37d9fd3c35f44fa58439fa41b4cdff2d25a98.zip
Merge PR #19759
Fix for has_and_belongs_to_many & has_many_through associations
-rw-r--r--activerecord/CHANGELOG.md7
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb5
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb13
3 files changed, 24 insertions, 1 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 487195a2e0..c2f26bce70 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,10 @@
+* Improved partial writes with HABTM and has many through associations
+ to fire database query only if relation has been changed.
+
+ Fixes #19663.
+
+ *Mehmet Emin İNAÇ*
+
* Deprecate passing arguments and block at the same time to
`ActiveRecord::QueryMethods#select`.
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb
index 1f264d325a..8c90aea975 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -86,7 +86,10 @@ module ActiveRecord
end
def save_through_record(record)
- build_through_record(record).save!
+ association = build_through_record(record)
+ if association.changed?
+ association.save!
+ end
ensure
@through_records.delete(record.object_id)
end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index 8aab7cfa47..6bded77eb2 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -1012,4 +1012,17 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
user = User.create!
assert_nothing_raised { user.jobs_pool.clear }
end
+
+ def test_has_and_belongs_to_many_while_partial_writes_false
+ begin
+ original_partial_writes = ActiveRecord::Base.partial_writes
+ ActiveRecord::Base.partial_writes = false
+ developer = Developer.new(name: "Mehmet Emin İNAÇ")
+ developer.projects << Project.new(name: "Bounty")
+
+ assert developer.save
+ ensure
+ ActiveRecord::Base.partial_writes = original_partial_writes
+ end
+ end
end