Preloader incorrectly reuses loaded associations when preloading unscoped and scoped has_many :through through the same join table
Author: mugitti9Created Jun 25, 2026Updated Sep 23, 2026
Labelsstale
When preloading both an unscoped and a scoped has_many :through association through the same join table, the scoped association incorrectly reuses the unscoped association's loaded records.
Steps to reproduce
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
create_table :posts, force: true
create_table :taggings, force: true do |t|
t.integer :post_id, null: false
t.integer :tag_id, null: false
end
create_table :tags, force: true do |t|
t.boolean :active, default: true, null: false
end
end
class Post < ActiveRecord::Base
has_many :taggings
has_many :tags, through: :taggings
has_many :inactive_tags, -> { where(active: false) }, through: :taggings, source: :tag
end
class Tagging < ActiveRecord::Base
belongs_to :post
belongs_to :tag
end
class Tag < ActiveRecord::Base
end
class PreloaderScopedHasManyThroughBugTest < ActiveSupport::TestCase
def test_preloading_unscoped_and_scoped_has_many_through_on_the_same_join_table
post = Post.create!
Tagging.create!(post: post, tag: Tag.create!(active: true))
Tagging.create!(post: post, tag: Tag.create!(active: true))
Tagging.create!(post: post, tag: Tag.create!(active: false))
result = Post.preload(:tags, :inactive_tags).find(post.id)
assert_equal 3, result.tags.size
assert_equal 1, result.inactive_tags.size, <<~MSG
Expected inactive_tags to return only inactive tags, but got #{result.inactive_tags.size}.
tags: #{result.tags.map { |tag| "Tag##{tag.id}(active=#{tag.active})" }.join(", ")}
inactive_tags: #{result.inactive_tags.map { |tag| "Tag##{tag.id}(active=#{tag.active})" }.join(", ")}
MSG
end
endExpected behavior
result.tags.size # => 3
result.inactive_tags.size # => 1Actual behavior
result.tags.size # => 3
result.inactive_tags.size # => 3After preloading the unscoped :tags association, the scoped :inactive_tags association (through the same join table, :taggings) ignores its scope and reuses the unscoped association's loaded records.
System configuration
Rails version: 8.2.0.alpha (main)
Ruby version: 3.3.8
Source: rails/rails