Last active
October 5, 2016 20:23
-
-
Save zorab47/c06349d953987569c32efb6c731de124 to your computer and use it in GitHub Desktop.
Reprodusable issue when eager loading relations from the same source
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", github: "rails/rails" | |
gem "sqlite3" | |
end | |
require "active_record" | |
require "minitest/autorun" | |
require "logger" | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
# Schema | |
ActiveRecord::Schema.define do | |
ActiveRecord::Base.connection.create_table(:companies) | |
ActiveRecord::Base.connection.create_table(:blogs) do |t| | |
t.integer :company_id | |
end | |
ActiveRecord::Base.connection.create_table(:posts) do |t| | |
t.integer :blog_id | |
t.string :title | |
t.boolean :promoted, default: false, null: false | |
end | |
end | |
# Models | |
class Company < ActiveRecord::Base | |
has_many :blogs | |
has_many :posts, through: :blogs | |
has_many :promoted_posts, -> { promoted }, through: :blogs, source: :posts | |
end | |
class Blog < ActiveRecord::Base | |
belongs_to :company | |
has_many :posts | |
end | |
class Post < ActiveRecord::Base | |
belongs_to :blog | |
scope :promoted, -> { where(promoted: true) } | |
end | |
class BugTest < Minitest::Test | |
def test_eager_load_different_relations_with_same_source | |
company = Company.create! | |
blog = Blog.create!(company: company) | |
post = blog.posts.create!(title: "Regular Post", promoted: false) | |
promoted_post = blog.posts.create!(title: "Promoted Post", promoted: true) | |
company = Company.includes(:posts).includes(:promoted_posts).first | |
assert_equal([promoted_post], company.promoted_posts.to_a, "Only a company's promoted posts should be returned") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment