From f798cbd2f36ed8a4b825667016d6975b812a5b9f Mon Sep 17 00:00:00 2001 From: akihiro17 Date: Tue, 21 Jul 2015 01:31:48 +0900 Subject: Don't cache arguments in #find_by if they are an ActiveRecord::Relation In this commit, find_by doesn't cache arguments so that find_by with association subquery works correctly. Fixes #20817 --- activerecord/CHANGELOG.md | 6 ++++++ activerecord/lib/active_record/core.rb | 2 +- activerecord/test/cases/finder_test.rb | 6 ++++++ 3 files changed, 13 insertions(+), 1 deletion(-) (limited to 'activerecord') diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 6a40d32ef9..cc19803c32 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,9 @@ +* Don't cache arguments in #find_by if they are an ActiveRecord::Relation + + Fixes #20817 + + *Hiroaki Izu* + * Allow fixtures files to set the model class in the YAML file itself. To load the fixtures file `accounts.yml` as the `User` model, use: diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 894d18b79e..7f66c83c06 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -177,7 +177,7 @@ module ActiveRecord hash = args.first return super if hash.values.any? { |v| - v.nil? || Array === v || Hash === v + v.nil? || Array === v || Hash === v || Relation === v } # We can't cache Post.find_by(author: david) ...yet diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 307b68764e..6686ce012d 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -265,6 +265,12 @@ class FinderTest < ActiveRecord::TestCase assert_equal [Account], accounts.collect(&:class).uniq end + def test_find_by_association_subquery + author = authors(:david) + assert_equal author.post, Post.find_by(author: Author.where(id: author)) + assert_equal author.post, Post.find_by(author_id: Author.where(id: author)) + end + def test_take assert_equal topics(:first), Topic.take end -- cgit v1.2.3