rails icon indicating copy to clipboard operation
rails copied to clipboard

Find with array returns nothing if primary key is not selected

Open fschwahn opened this issue 1 year ago • 0 comments

Steps to reproduce

When select is used and the primary key is not selected, the array form of find just returns an empty array.

begin
  require "bundler/inline"
rescue LoadError => e
  $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
  raise e
end

gemfile(true) do
  source "https://rubygems.org"
  gem "activerecord", "~> 7.0.0"
  gem "sqlite3"
end

require "active_record"
require "minitest/autorun"
require "logger"

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :users, force: true do |t|
    t.string :first_name
    t.string :last_name
    t.timestamps
  end
end

class User < ActiveRecord::Base
  def name
    "#{first_name} #{last_name}"
  end
end

class BugTest < Minitest::Test
  def test_find_returns_nothing
    user1 = User.create!(first_name: "John", last_name: "Doe")
    user2 = User.create!(first_name: "Jane", last_name: "Doe")

    assert_equal User.select(:first_name, :last_name).find([user1.id, user2.id]).map(&:name), ["John Doe", "Jane Doe"]
  end
end

Expected behavior

I think this should either raise (asking users to include the primary key), or automatically add the primary key to the selected columns. It could also just return the records, but in that case order is not guaranteed anymore, which might be surprising to users.

Actual behavior

An empty array is returned. In rails 6.1 this raised a KeyError which is also pretty confusing (and was the reason I originally investigated this).

System configuration

Rails version: 7.0.3.1

Ruby version: 2.7.4

fschwahn avatar Jul 29 '22 12:07 fschwahn