Skip to content
This repository
Browse code

Merge pull request #7661 from ernie/build-join-records-on-unsaved-hmt

Fix collection= on hm:t join models when unsaved
  • Loading branch information...
commit 82d507b4c37ff3a770a0c90424d73e967328094c 2 parents 896594f + 610b632
Rafael Mendonça França authored September 17, 2012
5  activerecord/CHANGELOG.md
Source Rendered
... ...
@@ -1,5 +1,10 @@
1 1
 ## Rails 4.0.0 (unreleased) ##
2 2
 
  3
+*   Fix creation of through association models when using collection=[]
  4
+    on a hm:t association from an unsaved model.
  5
+
  6
+    *Ernie Miller*
  7
+
3 8
 *   Explain only normal CRUD sql (select / update / insert / delete).
4 9
     Fix problem that explains unexplainable sql. Closes #7544 #6458.
5 10
 
14  activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -37,6 +37,20 @@ def concat(*records)
37 37
         super
38 38
       end
39 39
 
  40
+      def concat_records(records)
  41
+        ensure_not_nested
  42
+
  43
+        records = super
  44
+
  45
+        if owner.new_record? && records
  46
+          records.flatten.each do |record|
  47
+            build_through_record(record)
  48
+          end
  49
+        end
  50
+
  51
+        records
  52
+      end
  53
+
40 54
       def insert_record(record, validate = true, raise = false)
41 55
         ensure_not_nested
42 56
 
5  activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -838,6 +838,11 @@ def test_save_should_not_raise_exception_when_join_record_has_errors
838 838
     end
839 839
   end
840 840
 
  841
+  def test_assign_array_to_new_record_builds_join_records
  842
+    c = Category.new(:name => 'Fishing', :authors => [Author.first])
  843
+    assert_equal 1, c.categorizations.size
  844
+  end
  845
+
841 846
   def test_create_bang_should_raise_exception_when_join_record_has_errors
842 847
     repair_validations(Categorization) do
843 848
       Categorization.validate { |r| r.errors[:base] << 'Invalid Categorization' }

0 notes on commit 82d507b

Please sign in to comment.
Something went wrong with that request. Please try again.