Created
December 10, 2019 20:00
-
-
Save Edouard-chin/70744fa2debac416feab352a9ccc2bd1 to your computer and use it in GitHub Desktop.
Through association preloading doesn't work
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
# frozen_string_literal: true | |
require "bundler/inline" | |
gemfile(true) do | |
gem "rails", '~> 6.0.0' | |
gem "sqlite3" | |
end | |
require "active_record" | |
require "minitest/autorun" | |
require "logger" | |
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") | |
ActiveRecord::Schema.define do | |
create_table :users, force: true | |
create_table :accounts, force: true do |t| | |
t.integer :is_not_deleted, default: true | |
end | |
create_table :memberships, force: true do |t| | |
t.integer :user_id | |
t.integer :account_id | |
end | |
end | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
end | |
class User < ApplicationRecord | |
has_many :memberships, inverse_of: :user | |
has_many :accounts, through: :memberships | |
def primary_email | |
memberships.first.account | |
end | |
end | |
class Account < ApplicationRecord | |
has_many :memberships, inverse_of: :account | |
has_many :users, through: :memberships | |
default_scope { where(is_not_deleted: true) } # Comment this line to make the test pass | |
end | |
class Membership < ApplicationRecord | |
belongs_to :user, inverse_of: :memberships | |
belongs_to :account, inverse_of: :memberships | |
end | |
class BugTest < Minitest::Test | |
def test_association_stuff | |
account = Account.create! | |
user = User.create! | |
user.accounts << account | |
q_count = count_sql_queries do | |
users = User.preload(:accounts) | |
users.first.primary_email | |
end | |
assert_equal 3, q_count | |
end | |
def count_sql_queries(&block) | |
count = 0 | |
counter_f = ->(_, _, _, _, payload) { | |
unless (%w[CACHE SCHEMA]).include?(payload[:name]) | |
puts payload[:sql] | |
count += 1 | |
end | |
} | |
ActiveSupport::Notifications.subscribed(counter_f, "sql.active_record", &block) | |
count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment