Skip to content

Instantly share code, notes, and snippets.

@jturkel
Created June 30, 2014 00:32
Show Gist options
  • Save jturkel/e3850efcd8d699f99b85 to your computer and use it in GitHub Desktop.
Save jturkel/e3850efcd8d699f99b85 to your computer and use it in GitHub Desktop.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'arel', github: 'rails/arel'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
# 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
t.string :title
end
end
# Models
class Blog < ActiveRecord::Base
has_many :posts, -> { from('(select posts.* from posts where posts.title is not null) posts') }
end
class Post < ActiveRecord::Base
belongs_to :blog
end
class BugTest < Minitest::Test
def test_eager_load_with_from
blog = Blog.create!
post1 = blog.posts.create!(title: 'eager loading')
post2 = blog.posts.create!(title: nil)
# Make sure it works without eager loading
assert_equal([post1], Blog.first.posts.to_a)
# Now try it with eager loading
assert_equal([post1], Blog.includes(:posts).first.posts.to_a)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment