Skip to content

Commit

Permalink
Merge pull request #4543 from jdelStrother/find_or_init
Browse files Browse the repository at this point in the history
Don't instantiate two objects in collection proxy / find_or_instantiate_by
  • Loading branch information
jonleighton committed Feb 1, 2012
2 parents 56ba210 + ee2ae37 commit 66fc1d6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,8 @@ def method_missing(method, *args, &block)
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)
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/associations/has_many_associations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,18 @@ def test_find_or_initialize_updates_collection_size
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')
Expand Down

0 comments on commit 66fc1d6

Please sign in to comment.