From 9d109302f139a23d18de605454074777b995e4c4 Mon Sep 17 00:00:00 2001 From: Jon Buda Date: Tue, 27 Jul 2010 20:04:36 -0500 Subject: [PATCH] fixed joining of attributes when using find_or_create_by with multiple attributes through an association Signed-off-by: Santiago Pastorino --- .../active_record/associations/association_collection.rb | 2 +- .../cases/associations/has_many_associations_test.rb | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 4ce3b34819bfa..b5159eead3da4 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -422,7 +422,7 @@ def method_missing(method, *args) match = DynamicFinderMatch.match(method) if match && match.creator? attributes = match.attribute_names - return send(:"find_by_#{attributes.join('and')}", *args) || create(Hash[attributes.zip(args)]) + return send(:"find_by_#{attributes.join('_and_')}", *args) || create(Hash[attributes.zip(args)]) end if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method)) diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 6fe737a8170a1..ac2021c3697b1 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -167,6 +167,15 @@ def test_dynamic_find_all_should_respect_readonly_access companies(:first_firm).readonly_clients.find(:all).each { |c| assert c.readonly? } end + def test_dynamic_find_or_create_from_two_attributes_using_an_association + author = authors(:david) + number_of_posts = Post.count + another = author.posts.find_or_create_by_title_and_body("Another Post", "This is the Body") + assert_equal number_of_posts + 1, Post.count + assert_equal another, author.posts.find_or_create_by_title_and_body("Another Post", "This is the Body") + assert !another.new_record? + end + def test_cant_save_has_many_readonly_association authors(:david).readonly_comments.each { |c| assert_raise(ActiveRecord::ReadOnlyRecord) { c.save! } } authors(:david).readonly_comments.each { |c| assert c.readonly? }