Created
March 5, 2016 18:45
-
-
Save jturkel/fc4cca3949724da4b902 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 '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| | |
| end | |
| ActiveRecord::Base.connection.create_table(:addresses) do |t| | |
| t.string :city | |
| t.integer :author_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 | |
| blog = Blog.create! | |
| author = Author.create! | |
| Address.create!(author: author, city: 'Boston') | |
| blog.posts.create(author: author) | |
| # Without eager loading | |
| assert_equal([author], Blog.first.authors) | |
| # With eager loading | |
| assert_equal([author], 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