From 610b63288f05bdec677bfd78c546ee085e5184b9 Mon Sep 17 00:00:00 2001 From: Ernie Miller Date: Sun, 16 Sep 2012 21:23:58 -0400 Subject: Fix collection= on hm:t join models when unsaved If assigning to a has_many :through collection against an unsaved object using the collection=[] syntax, the join models were not properly created, previously. --- activerecord/CHANGELOG.md | 5 +++++ .../associations/has_many_through_association.rb | 14 ++++++++++++++ .../associations/has_many_through_associations_test.rb | 5 +++++ 3 files changed, 24 insertions(+) (limited to 'activerecord') diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index a4ba956477..ef059e5d3c 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,5 +1,10 @@ ## Rails 4.0.0 (unreleased) ## +* Fix creation of through association models when using collection=[] + on a hm:t association from an unsaved model. + + *Ernie Miller* + * Explain only normal CRUD sql (select / update / insert / delete). Fix problem that explains unexplainable sql. Closes #7544 #6458. 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 88ff11f953..d8f14c896c 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -37,6 +37,20 @@ module ActiveRecord super end + def concat_records(records) + ensure_not_nested + + records = super + + if owner.new_record? && records + records.flatten.each do |record| + build_through_record(record) + end + end + + records + end + def insert_record(record, validate = true, raise = false) ensure_not_nested diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 36e5ba9660..c591fd8532 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -838,6 +838,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end end + def test_assign_array_to_new_record_builds_join_records + c = Category.new(:name => 'Fishing', :authors => [Author.first]) + assert_equal 1, c.categorizations.size + end + def test_create_bang_should_raise_exception_when_join_record_has_errors repair_validations(Categorization) do Categorization.validate { |r| r.errors[:base] << 'Invalid Categorization' } -- cgit v1.2.3