From 6e599ee099ce9beeddfc938574225b943c144bd8 Mon Sep 17 00:00:00 2001
From: Ryuta Kamizono <kamipo@gmail.com>
Date: Fri, 22 Feb 2019 06:14:33 +0900
Subject: Fix `pluck` and `select` with `from` if `from` has original table
 name

This is caused by 0ee96d1.

Since #18744, `select` columns doesn't be qualified by table name if
using `from`. 0ee96d1 follows that for `pluck` as well.

But people depends that `pluck` columns are qualified even if using
`from`.

So I've fixed that to be qualified if `from` has the original table name
to keep the behavior as much as before.

Fixes #35359.
---
 activerecord/test/cases/relations_test.rb | 36 +++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)

(limited to 'activerecord/test')

diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index adc50a694e..8f97311eaf 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -182,6 +182,42 @@ class RelationTest < ActiveRecord::TestCase
     end
   end
 
+  def test_select_with_original_table_name_in_from
+    relation = Comment.joins(:post).select(:id).order(:id)
+    subquery = Comment.from(Comment.table_name).joins(:post).select(:id).order(:id)
+    assert_equal relation.map(&:id), subquery.map(&:id)
+  end
+
+  def test_pluck_with_original_table_name_in_from
+    relation = Comment.joins(:post).order(:id)
+    subquery = Comment.from(Comment.table_name).joins(:post).order(:id)
+    assert_equal relation.pluck(:id), subquery.pluck(:id)
+  end
+
+  def test_select_with_quoted_original_table_name_in_from
+    relation = Comment.joins(:post).select(:id).order(:id)
+    subquery = Comment.from(Comment.quoted_table_name).joins(:post).select(:id).order(:id)
+    assert_equal relation.map(&:id), subquery.map(&:id)
+  end
+
+  def test_pluck_with_quoted_original_table_name_in_from
+    relation = Comment.joins(:post).order(:id)
+    subquery = Comment.from(Comment.quoted_table_name).joins(:post).order(:id)
+    assert_equal relation.pluck(:id), subquery.pluck(:id)
+  end
+
+  def test_select_with_subquery_in_from_uses_original_table_name
+    relation = Comment.joins(:post).select(:id).order(:id)
+    subquery = Comment.from(Comment.all, Comment.quoted_table_name).joins(:post).select(:id).order(:id)
+    assert_equal relation.map(&:id), subquery.map(&:id)
+  end
+
+  def test_pluck_with_subquery_in_from_uses_original_table_name
+    relation = Comment.joins(:post).order(:id)
+    subquery = Comment.from(Comment.all, Comment.quoted_table_name).joins(:post).order(:id)
+    assert_equal relation.pluck(:id), subquery.pluck(:id)
+  end
+
   def test_select_with_subquery_in_from_does_not_use_original_table_name
     relation = Comment.group(:type).select("COUNT(post_id) AS post_count, type")
     subquery = Comment.from(relation).select("type", "post_count")
-- 
cgit v1.2.3