Skip to content

Instantly share code, notes, and snippets.

@jturkel
Last active March 6, 2016 03:28
Show Gist options
  • Select an option

  • Save jturkel/447257f08372a80e6893 to your computer and use it in GitHub Desktop.

Select an option

Save jturkel/447257f08372a80e6893 to your computer and use it in GitHub Desktop.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', '4.1.14.2' # '4.0.13' # '4.2.5.2' '4.1.14.2'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
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(:posts) do |t|
t.integer :author_id
t.integer :blog_id
end
ActiveRecord::Base.connection.create_table(:authors) do |t|
t.string :name
end
end
# Models
class Blog < ActiveRecord::Base
has_many :posts
has_many :authors, -> do
joins(:posts).order('authors.name').order('posts.blog_id')
end, through: :posts
end
class Post < ActiveRecord::Base
belongs_to :author
belongs_to :blog
end
class Author < ActiveRecord::Base
has_many :posts
end
class BugTest < Minitest::Test
def test_bug
blog = Blog.create!
frank = Author.create!(name: 'frank')
blog.posts.create(author: frank)
bob = Author.create!(name: 'bob')
blog.posts.create(author: bob)
# Without eager loading
assert_equal([bob, frank], Blog.first.authors)
# With eager loading
assert_equal([bob, frank], Blog.includes(:authors).first.authors)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment