rails icon indicating copy to clipboard operation
rails copied to clipboard

Array primary keys (e.g. composite) break `collection_singular_ids` method when using preload

Open Slotos opened this issue 3 months ago • 2 comments

Steps to reproduce

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem "rails"
  # If you want to test against edge Rails replace the previous line with this:
  # gem "rails", github: "rails/rails", branch: "main"

  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 :posts, force: true do |t|
  end

  create_table :comments, force: true do |t|
    t.integer :post_id
  end
end

class Post < ActiveRecord::Base
  self.primary_key = [:id]
  has_many :comments
end

class Comment < ActiveRecord::Base
  self.primary_key = [:id]
  belongs_to :post
end

class BugTest < Minitest::Test
  def test_association_stuff
    post = Post.create!
    post.comments.create!

    assert_equal 1, post.comments.count
    assert_equal 1, Comment.count
    assert_equal post.id, Comment.take.post.id

    assert_equal Comment.ids, Post.take.comment_ids
    assert_equal Comment.ids, Post.preload(:comments).take.comment_ids
  end
end

Expected behavior

collection_singular_ids should work the same when preloading or not.

Actual behavior

Preloaded associations' collection_singular_ids returns an array of nil values when association was preloaded.

Analysis

The problem lies in different handling of array arguments to Enumerable#pluck and ActiveRecord::Relation#pluck:

      def ids_reader
        if loaded?
          target.pluck(reflection.association_primary_key) # -> Enumerable#pluck
        elsif !target.empty?
          load_target.pluck(reflection.association_primary_key) # -> Enumerable#pluck
        else
          @association_ids ||= scope.pluck(reflection.association_primary_key) # -> ActiveRecord::Relation#pluck
        end
      end

ActiveRecord::Relation#pluck efectively flattens its arguments in #arel_columns call, whereas Enumerable#pluck uses them as is.

Incidentally, arguments flattening results in column names not being processed with #arel_column.

System configuration

Rails version: 7.1

Ruby version: 3.3.0

Slotos avatar Feb 19 '24 18:02 Slotos