Last active
March 20, 2021 15:54
-
-
Save tbuehlmann/2889423ede5d73d4a56a91a3ea1a3fd6 to your computer and use it in GitHub Desktop.
This file contains 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
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(false) do | |
source 'https://rubygems.org' | |
git_source(:github) { |repo| "https://github.com/#{repo}.git" } | |
gem 'activerecord', '6.1.3' | |
gem 'activestorage', '6.1.3' | |
gem 'rails', '6.1.3' | |
gem 'pg', '>= 0.18', '< 2.0' | |
gem 'rspec' | |
gem 'pry' | |
end | |
require 'active_record' | |
require 'active_storage' | |
require 'rspec' | |
ActiveRecord::Tasks::DatabaseTasks.drop('adapter' => 'postgresql', 'database' => 'items-test') | |
ActiveRecord::Tasks::DatabaseTasks.create('adapter' => 'postgresql', 'database' => 'items-test') | |
ActiveRecord::Base.establish_connection('adapter' => 'postgresql', 'database' => 'items-test') | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :categories do |t| | |
t.timestamps | |
end | |
create_table :items do |t| | |
t.belongs_to :category | |
t.timestamps | |
end | |
end | |
class Category < ActiveRecord::Base | |
has_many :items | |
end | |
class Item < ActiveRecord::Base | |
belongs_to :category | |
scope :five_per_category, -> { | |
from('(SELECT *, ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY category_id) FROM items) AS items').where('row_number <= 5') | |
} | |
end | |
RSpec.describe do | |
before do | |
category_1 = Category.create! | |
category_2 = Category.create! | |
4.times { category_1.items.create! } | |
6.times { category_2.items.create! } | |
end | |
it 'preloading works, nice' do | |
categories = Category.all | |
items = Item.five_per_category.where(category: categories) | |
ActiveRecord::Associations::Preloader.new.preload(categories, :items, items) | |
expect(categories[0].items.size).to eq(4) | |
expect(categories[1].items.size).to eq(5) | |
end | |
end | |
RSpec::Core::Runner.invoke |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment