Skip to content

Instantly share code, notes, and snippets.

@jturkel
Created July 24, 2020 18:25
Show Gist options
  • Save jturkel/5c2714b008b9d07c1de59ce15b125cce to your computer and use it in GitHub Desktop.
Save jturkel/5c2714b008b9d07c1de59ce15b125cce 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', github: 'rails/rails'
gem 'sqlite3'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
puts "Using ActiveRecord #{ActiveRecord::VERSION::STRING}"
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
# Schema
ActiveRecord::Schema.define do
ActiveRecord::Base.connection.create_table(:blogs)
ActiveRecord::Base.connection.create_table(:posts) do |t|
t.integer :blog_id
end
end
# Models
class Blog < ActiveRecord::Base
has_many :posts
has_many :limited_posts, -> { order(:id).limit(2) }, class_name: 'Post'
has_many :offset_posts, -> { offset(1) }, class_name: 'Post'
end
class Post < ActiveRecord::Base
belongs_to :blog
end
class BugTest < Minitest::Test
def setup
Blog.delete_all
Post.delete_all
end
def test_eager_load_association_with_limit
blog1 = Blog.create!
blog_1_limited_posts = Array.new(3) { blog1.posts.create! }.take(2)
blog2 = Blog.create!
blog_2_limited_posts = Array.new(3) { blog2.posts.create! }.take(2)
blogs = Blog.includes(:limited_posts).order(:id).to_a
assert_equal(blog_1_limited_posts, blogs.first.limited_posts.to_a)
assert_equal(blog_2_limited_posts, blogs.second.limited_posts.to_a)
end
def test_eager_load_association_with_offset
blog1 = Blog.create!
blog_1_offset_posts = Array.new(3) { blog1.posts.create! }.drop(1)
blog2 = Blog.create!
blog_2_offset_posts = Array.new(3) { blog2.posts.create! }.drop(1)
blogs = Blog.includes(:offset_posts).order(:id).to_a
assert_equal(blog_1_offset_posts, blogs.first.offset_posts.to_a)
assert_equal(blog_2_offset_posts, blogs.second.offset_posts.to_a)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment