Merge pull request #45931 from fatkodima/follow-up-45695

Do not mutate relation when implicitly selecting a primary key in `ActiveRecord.find`
This commit is contained in:
Jean Boussier 2022-09-02 16:05:57 +02:00 committed by GitHub
commit fa50226fcf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 6 deletions

View File

@ -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) })

View File

@ -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)