Created
July 10, 2018 19:01
-
-
Save jturkel/8693bd3e07db2cbe92b034677dfa2491 to your computer and use it in GitHub Desktop.
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
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 'rails', '~> 5.2.0' # Fails in '~> 5.1.0' | |
gem 'sqlite3', '1.3.12' | |
gem 'goldiloader' | |
end | |
require 'active_record' | |
require 'minitest/autorun' | |
require 'logger' | |
puts "Using ActiveRecord #{ActiveRecord::VERSION::STRING}" | |
# Ensure backward compatibility with Minitest 4 | |
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
# Schema | |
ActiveRecord::Schema.define do | |
ActiveRecord::Base.connection.create_table(:blogs) do |t| | |
end | |
ActiveRecord::Base.connection.create_table(:authors) do |t| | |
end | |
ActiveRecord::Base.connection.create_table(:addresses) do |t| | |
t.integer :author_id | |
t.string :city | |
end | |
ActiveRecord::Base.connection.create_table(:posts) do |t| | |
t.integer :author_id | |
t.integer :blog_id | |
end | |
end | |
# Models | |
class Blog < ActiveRecord::Base | |
has_many :posts | |
has_many :authors, -> { includes(:address).where('addresses.city IS NOT NULL').references(:address) }, through: :posts | |
end | |
class Post < ActiveRecord::Base | |
belongs_to :blog | |
belongs_to :author | |
end | |
class Author < ActiveRecord::Base | |
has_many :posts | |
has_one :address | |
end | |
class Address < ActiveRecord::Base | |
belongs_to :author | |
end | |
class BugTest < Minitest::Test | |
def test_bug | |
author1 = Author.create! | |
Address.create(city: 'Boston', author: author1) | |
blog = Blog.create! | |
post1 = blog.posts.create!(author: author1) | |
post2 = blog.posts.create!(author: author1) | |
cityless_author = Author.create! | |
blog.posts.create!(author: cityless_author) | |
# Explicit eager loading | |
authors = Blog.includes(:authors).flat_map(&:authors).compact.sort_by(&:id) | |
assert_equal([author1, author1], authors) | |
# Automatic eager loading | |
authors = Blog.all.flat_map(&:authors).compact.sort_by(&:id) | |
assert_equal([author1, author1], authors) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment