Skip to content

Instantly share code, notes, and snippets.

@onyxblade
Created August 9, 2017 06:48
Show Gist options
  • Select an option

  • Save onyxblade/499e0669313043a44ff0b87db0988706 to your computer and use it in GitHub Desktop.

Select an option

Save onyxblade/499e0669313043a44ff0b87db0988706 to your computer and use it in GitHub Desktop.
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", path: "./rails"
gem "arel", path: "./arel"
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)
ActiveRecord::Schema.define do
create_table :hotels, force: true do |t|
end
create_table :departments, force: true do |t|
t.integer :hotel_id
end
create_table :cake_designers, force: true do |t|
end
create_table :drink_designers, force: true do |t|
end
create_table :chefs, force: true do |t|
t.integer :employable_id
t.string :employable_type
t.integer :department_id
t.string :employable_list_type
t.integer :employable_list_id
end
end
class Hotel < ActiveRecord::Base
has_many :departments
has_many :chefs, through: :departments
has_many :cake_designers, source_type: "CakeDesigner", source: :employable, through: :chefs
has_many :drink_designers, source_type: "DrinkDesigner", source: :employable, through: :chefs
end
class Department < ActiveRecord::Base
has_many :chefs
belongs_to :hotel
end
class Chef < ActiveRecord::Base
belongs_to :employable, polymorphic: true
has_many :recipes
end
class CakeDesigner < ActiveRecord::Base
has_one :chef, as: :employable
end
class DrinkDesigner < ActiveRecord::Base
has_one :chef, as: :employable
end
class BugTest < Minitest::Test
def test_eager_loading_polymorphic_source
hotel = Hotel.create!
department = hotel.departments.create!
cake_designer = CakeDesigner.create!
drink_designer = DrinkDesigner.create!
chef_a = department.chefs.create!(employable: cake_designer)
chef_b = department.chefs.create!(employable: drink_designer)
hotel = Hotel.eager_load(:cake_designers, :drink_designers).find(hotel.id)
assert_equal 1, hotel.cake_designers.size
assert_equal cake_designer, hotel.cake_designers.first
assert_equal 1, hotel.drink_designers.size
assert_equal drink_designer, hotel.drink_designers.first
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment