Skip to content

Instantly share code, notes, and snippets.

@Edouard-chin
Last active May 25, 2020 15:12
Show Gist options
  • Save Edouard-chin/af5511a7544afe9596fabdb1da24fc3e to your computer and use it in GitHub Desktop.
Save Edouard-chin/af5511a7544afe9596fabdb1da24fc3e to your computer and use it in GitHub Desktop.
Preload polymorphic association with scope
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "sqlite3"
gem 'activerecord', github: 'rails/rails', ref: ENV['REF']
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)
ActiveRecord::Schema.define do
create_table :pictures, force: true do |t|
t.references :imageable, polymorphic: true
end
create_table :employees, force: true do |t|
t.string :name
t.boolean :active, default: 1
end
end
class Picture < ActiveRecord::Base
belongs_to :imageable, -> { where(active: true) }, polymorphic: true
end
class Employee < ActiveRecord::Base
has_many :pictures, as: :imageable
end
class BugTest < Minitest::Test
def test_preload_polymorphic_association
employee = Employee.create!(name: 'John')
picture = Picture.create!(imageable: employee)
picture.association(:imageable).reset # Reset the association, otherwise `.preload` will return a `AlreadyLoaded` association
Picture.preload(:imageable).first
end
end
@Edouard-chin
Copy link
Author

Edouard-chin commented May 25, 2020

Previous behaviour = REF=3523516fab1172be195c72d3280ef582fc0ea1a7 bundle exec ruby bug.rb
Current behaviour = REF=489df7e bundle exec ruby bug.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment