public
Description: Ruby on Rails
Homepage: http://rubyonrails.org
Clone URL: git://github.com/rails/rails.git
Add block syntax to HasManyAssociation#build. [#502 state:resolve]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
jasondew (author)
Fri Jun 27 09:25:26 -0700 2008
lifo (committer)
Sun Jul 13 18:24:12 -0700 2008
commit  c6f397c5cecf183680c191dd2128c0a96c5b9399
tree    574b28103b2f9cb416cb7be9304f1a3f2adfc0d7
parent  d72c66532f959846cdc2d7fb1dc1ef6ba87bdcb1
...
78
79
80
81
 
82
83
 
84
85
 
 
 
 
86
87
88
...
78
79
80
 
81
82
 
83
84
 
85
86
87
88
89
90
91
0
@@ -78,11 +78,14 @@ module ActiveRecord
0
         @loaded = false
0
       end
0
 
0
-      def build(attributes = {})
0
+      def build(attributes = {}, &block)
0
         if attributes.is_a?(Array)
0
-          attributes.collect { |attr| build(attr) }
0
+          attributes.collect { |attr| build(attr, &block) }
0
         else
0
-          build_record(attributes) { |record| set_belongs_to_association_for(record) }
0
+          build_record(attributes) do |record|
0
+            block.call(record) if block_given?
0
+            set_belongs_to_association_for(record)
0
+          end
0
         end
0
       end
0
 
...
425
426
427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
429
430
...
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
0
@@ -425,6 +425,37 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
0
     assert_equal 2, first_topic.replies.to_ary.size
0
   end
0
 
0
+  def test_build_via_block
0
+    company = companies(:first_firm)
0
+    new_client = assert_no_queries { company.clients_of_firm.build {|client| client.name = "Another Client" } }
0
+    assert !company.clients_of_firm.loaded?
0
+
0
+    assert_equal "Another Client", new_client.name
0
+    assert new_client.new_record?
0
+    assert_equal new_client, company.clients_of_firm.last
0
+    company.name += '-changed'
0
+    assert_queries(2) { assert company.save }
0
+    assert !new_client.new_record?
0
+    assert_equal 2, company.clients_of_firm(true).size
0
+  end
0
+
0
+  def test_build_many_via_block
0
+    company = companies(:first_firm)
0
+    new_clients = assert_no_queries do
0
+      company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
0
+        client.name = "changed"
0
+      end
0
+    end
0
+
0
+    assert_equal 2, new_clients.size
0
+    assert_equal "changed", new_clients.first.name
0
+    assert_equal "changed", new_clients.last.name
0
+
0
+    company.name += '-changed'
0
+    assert_queries(3) { assert company.save }
0
+    assert_equal 3, company.clients_of_firm(true).size
0
+  end
0
+
0
   def test_create_without_loading_association
0
     first_firm  = companies(:first_firm)
0
     Firm.column_names

Comments