Skip to content

Instantly share code, notes, and snippets.

@intrip
Last active February 17, 2021 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrip/028fa8635104423cf33302e0ce832fda to your computer and use it in GitHub Desktop.
Save intrip/028fa8635104423cf33302e0ce832fda to your computer and use it in GitHub Desktop.
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem 'rails', '6.1'
gem 'sqlite3'
end
require 'active_record'
require 'minitest/autorun'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :users do |t|
t.references :user_comments
end
create_table :user_comments do |t|
t.references :user
t.references :comment
end
create_table :comments do |t|
t.references :user_comments
t.boolean :published, default: false
end
end
class User < ActiveRecord::Base
has_many :user_comments
has_many :comments, through: :user_comments
has_many :published_comments, -> { published }, through: :user_comments, source: :comment
end
class UserComment < ActiveRecord::Base
belongs_to :comment
belongs_to :user
end
class Comment < ActiveRecord::Base
has_many :user_comments
scope :published, ->{ where(published: true) }
end
class BugTest < Minitest::Test
def test_preload_scoped
u = User.new
u.comments << Comment.new
u.comments << Comment.new(published: true)
u.save!
# this pass
assert_equal 1, User.preload(:published_comments, :comments).find(u.id).published_comments.size
assert_equal 1, User.eager_load(:comments, :published_comments).find(u.id).published_comments.size
# this fails, same applies for .includes which in this situation uses .preload as well
assert_equal 1, User.preload(:comments, :published_comments).find(u.id).published_comments.size
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment