Created
July 6, 2017 02:00
-
-
Save jturkel/84c50e76c1a6cc074d172ade4c97c19b 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
| 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.1.2' #github: 'rails/rails' | |
| gem 'sqlite3' | |
| 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(: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