diff options
author | Jon Leighton <j@jonathanleighton.com> | 2012-02-01 15:15:29 -0800 |
---|---|---|
committer | Jon Leighton <j@jonathanleighton.com> | 2012-02-01 23:19:25 +0000 |
commit | 42dab646eb10e8c7249ad875465679eaf9acc856 (patch) | |
tree | 1068fa484e5b6e161bc0b4243c3056c58dcf5d05 | |
parent | 780bf52085bf64f4d55b5e992fce3474f8f7ad70 (diff) | |
download | rails-42dab646eb10e8c7249ad875465679eaf9acc856.tar.gz rails-42dab646eb10e8c7249ad875465679eaf9acc856.tar.bz2 rails-42dab646eb10e8c7249ad875465679eaf9acc856.zip |
Merge pull request #4543 from jdelStrother/find_or_init
Don't instantiate two objects in collection proxy / find_or_instantiate_by
-rw-r--r-- | activerecord/lib/active_record/associations/collection_proxy.rb | 3 | ||||
-rw-r--r-- | activerecord/test/cases/associations/has_many_associations_test.rb | 12 |
2 files changed, 13 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index eb320bc774..416a5823c6 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -82,9 +82,8 @@ module ActiveRecord proxy_association.send :add_to_target, r yield(r) if block_given? end - end - if target.respond_to?(method) || (!proxy_association.klass.respond_to?(method) && Class.respond_to?(method)) + elsif target.respond_to?(method) || (!proxy_association.klass.respond_to?(method) && Class.respond_to?(method)) if load_target if target.respond_to?(method) target.send(method, *args, &block) diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 7146091270..0b03844d50 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -738,6 +738,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal number_of_clients + 1, companies(:first_firm).clients_of_firm.size end + def test_find_or_initialize_returns_the_instantiated_object + client = companies(:first_firm).clients_of_firm.find_or_initialize_by_name("name" => "Another Client") + assert_equal client, companies(:first_firm).clients_of_firm[-1] + end + + def test_find_or_initialize_only_instantiates_a_single_object + number_of_clients = Client.count + companies(:first_firm).clients_of_firm.find_or_initialize_by_name("name" => "Another Client").save! + companies(:first_firm).save! + assert_equal number_of_clients+1, Client.count + end + def test_find_or_create_with_hash post = authors(:david).posts.find_or_create_by_title(:title => 'Yet another post', :body => 'somebody') assert_equal post, authors(:david).posts.find_or_create_by_title(:title => 'Yet another post', :body => 'somebody') |