Created
June 24, 2014 01:27
-
-
Save jturkel/3ad3e3ebf28d9e77fdc5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
unless File.exist?('Gemfile') | |
File.write('Gemfile', <<-GEMFILE) | |
source 'https://rubygems.org' | |
gem 'rails', github: 'rails/rails' | |
gem 'arel', github: 'rails/arel' | |
gem 'sqlite3' | |
GEMFILE | |
system 'bundle' | |
end | |
require 'bundler' | |
Bundler.setup(:default) | |
require 'active_record' | |
require 'minitest/autorun' | |
require 'logger' | |
# 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) | |
ActiveRecord::Base.connection.create_table(:authors) do |t| | |
t.string :name | |
end | |
ActiveRecord::Base.connection.create_table(:posts) do |t| | |
t.integer :blog_id | |
t.integer :author_id | |
end | |
end | |
# Models | |
class Blog < ActiveRecord::Base | |
has_many :posts, -> { joins(:author).order('authors.name') } | |
end | |
class Post < ActiveRecord::Base | |
belongs_to :blog | |
belongs_to :author | |
end | |
class Author < ActiveRecord::Base | |
has_many :posts | |
end | |
class BugTest < Minitest::Test | |
def setup | |
Blog.delete_all | |
Post.delete_all | |
Author.delete_all | |
end | |
def test_eager_load_with_join | |
blog = Blog.create! | |
author = Author.create! | |
blog.posts.create!(author: author) | |
# Make sure it works without eager loading | |
assert_equal([author], Blog.all.to_a.flat_map(&:posts).map(&:author).to_a) | |
# Now try it with eager loading | |
assert_equal([author], Blog.includes(:posts).to_a.flat_map(&:posts).map(&:author).to_a) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment