Last active
May 25, 2020 15:12
-
-
Save Edouard-chin/af5511a7544afe9596fabdb1da24fc3e to your computer and use it in GitHub Desktop.
Preload polymorphic association with scope
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 | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Previous behaviour =
REF=3523516fab1172be195c72d3280ef582fc0ea1a7 bundle exec ruby bug.rb
Current behaviour =
REF=489df7e bundle exec ruby bug.rb