From 2714e21021f122bd0771e8c1be11f03761889fae Mon Sep 17 00:00:00 2001 From: fatkodima Date: Fri, 2 Sep 2022 16:35:37 +0300 Subject: [PATCH] Do not mutate relation when implicitly selecting a primary key in `ActiveRecord.find` --- .../lib/active_record/relation/finder_methods.rb | 9 ++++++--- activerecord/test/cases/finder_test.rb | 3 --- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 45515854c07..273f8491f97 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -448,7 +448,6 @@ module ActiveRecord ids = ids.flatten.compact.uniq model_name = @klass.name - _select!(table[primary_key]) unless select_values.empty? case ids.size when 0 @@ -481,7 +480,9 @@ module ActiveRecord def find_some(ids) return find_some_ordered(ids) unless order_values.present? - result = where(primary_key => ids).to_a + relation = where(primary_key => ids) + relation = relation.select(table[primary_key]) unless select_values.empty? + result = relation.to_a expected_size = if limit_value && ids.size > limit_value @@ -505,7 +506,9 @@ module ActiveRecord def find_some_ordered(ids) ids = ids.slice(offset_value || 0, limit_value || ids.size) || [] - result = except(:limit, :offset).where(primary_key => ids).records + relation = except(:limit, :offset).where(primary_key => ids) + relation = relation.select(table[primary_key]) unless select_values.empty? + result = relation.records if result.size == ids.size result.in_order_of(:id, ids.map { |id| @klass.type_for_attribute(primary_key).cast(id) }) diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 8d14d590ea7..e6559dc3960 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -53,9 +53,6 @@ class FinderTest < ActiveRecord::TestCase end def test_find_with_custom_select_excluding_id - topic = Topic.select(:title).find(4) - assert_equal 4, topic.id - # Returns ordered by ids array topics = Topic.select(:title).find([4, 2, 5]) assert_equal [4, 2, 5], topics.map(&:id)