Created
August 22, 2017 00:07
-
-
Save messanjah/d58df82efc01ef9b6cb5d9fcbdb3fb8d to your computer and use it in GitHub Desktop.
ActiveRecord 5.1.3 Bug report: Joins does not populate association_cache for all records.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
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" | |
# Activate the gem you are reporting the issue against. | |
gem "activerecord", "5.1.3" | |
gem "sqlite3" | |
end | |
require "active_record" | |
require "minitest/autorun" | |
require "logger" | |
# Ensure backward compatibility with Minitest 4 | |
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) | |
# 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 :authors, force: :true do |t| | |
end | |
create_table :posts, force: true do |t| | |
t.integer :author_id | |
end | |
create_table :comments, force: true do |t| | |
t.integer :post_id | |
end | |
end | |
class Author < ActiveRecord::Base | |
has_many :posts | |
end | |
class Post < ActiveRecord::Base | |
has_many :comments | |
belongs_to :author | |
end | |
class Comment < ActiveRecord::Base | |
belongs_to :post | |
end | |
class BugTest < Minitest::Test | |
def test_preload_association_cache_combined_with_joins | |
first_author = Author.create! | |
first_post = first_author.posts.create! | |
first_post.comments.create! | |
first_post.comments.create! | |
second_author = Author.create! | |
second_post = second_author.posts.create! | |
second_post.comments.create! | |
# The universe exists | |
assert_equal 2, first_post.comments.count | |
assert_equal 3, Comment.count | |
assert_equal 2, Post.count | |
assert_equal first_post.id, Comment.first.post.id | |
assert_equal second_post.id, Comment.last.post.id | |
# `post.author` is cached when no joins | |
Post.preload(:author).each do |post| | |
assert post.association_cached?(:author) | |
end | |
# Bug report: `post.author` is not cached when a join brings in | |
# a "duplicated" post. | |
posts = Post.joins(:comments).preload(:author) | |
refute_equal posts.first.author, posts.last.author | |
assert_equal posts.first.author, posts.second.author | |
posts.each do |post| | |
assert post.association_cached?(:author) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment