From cd0ed12d1a9edc73be953d700748b5827df890c7 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 4 Feb 2015 08:44:48 -0700 Subject: Respect custom primary keys for associations in `Relation#where` While we query the proper columns, we go through normal handling for converting the value to a primitive which assumes it should use the table's primary key. If the association specifies a different value (and we know that we're working with an association), we should use the custom primary key instead. Fixes #18813. --- activerecord/test/cases/relation/where_test.rb | 38 +++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) (limited to 'activerecord/test/cases') diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb index 537937decd..6af31017d6 100644 --- a/activerecord/test/cases/relation/where_test.rb +++ b/activerecord/test/cases/relation/where_test.rb @@ -5,6 +5,7 @@ require "models/cake_designer" require "models/chef" require "models/comment" require "models/edge" +require "models/essay" require "models/post" require "models/price_estimate" require "models/topic" @@ -13,7 +14,7 @@ require "models/vertex" module ActiveRecord class WhereTest < ActiveRecord::TestCase - fixtures :posts, :edges, :authors, :binaries + fixtures :posts, :edges, :authors, :binaries, :essays def test_where_copies_bind_params author = authors(:david) @@ -240,5 +241,40 @@ module ActiveRecord count = Binary.where(:data => 0).count assert_equal 0, count end + + def test_where_on_association_with_custom_primary_key + author = authors(:david) + essay = Essay.where(writer: author).first + + assert_equal essays(:david_modest_proposal), essay + end + + def test_where_on_association_with_custom_primary_key_with_relation + author = authors(:david) + essay = Essay.where(writer: Author.where(id: author.id)).first + + assert_equal essays(:david_modest_proposal), essay + end + + def test_where_on_association_with_relation_performs_subselect_not_two_queries + author = authors(:david) + + assert_queries(1) do + Essay.where(writer: Author.where(id: author.id)).to_a + end + end + + def test_where_on_association_with_custom_primary_key_with_array_of_base + author = authors(:david) + essay = Essay.where(writer: [author]).first + + assert_equal essays(:david_modest_proposal), essay + end + + def test_where_on_association_with_custom_primary_key_with_array_of_ids + essay = Essay.where(writer: ["David"]).first + + assert_equal essays(:david_modest_proposal), essay + end end end -- cgit v1.2.3