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
jeremy (committer)
Tue Jul 15 15:54:21 -0700 2008
commit  04f7ac59d23ccf1b4b29bac8d99f02e634001dee
tree    01fe09f50179b64941b571cd98ec59b04829aed4
parent  536400bfcf2eafc2f724b2a9dd899cd9bdb26f09
...
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
 
...
421
422
423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
425
426
...
421
422
423
424
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
0
@@ -421,6 +421,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