Skip to content

Instantly share code, notes, and snippets.

@jturkel
Last active August 29, 2015 14:09
Show Gist options
  • Save jturkel/82df7f9e4ccf96df14a5 to your computer and use it in GitHub Desktop.
Save jturkel/82df7f9e4ccf96df14a5 to your computer and use it in GitHub Desktop.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', '4.1.7' # Works with '4.0.11'
gem 'closure_tree'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'active_support/all'
require 'minitest/autorun'
require 'logger'
require 'closure_tree'
# 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(:categories) do |t|
t.string :name
t.integer :parent_id
end
ActiveRecord::Base.connection.create_table(:category_hierarchies) do |t|
t.integer :ancestor_id, null: false
t.integer :descendant_id, null: false
t.integer :generations, null: false
end
end
# Models
class Category < ActiveRecord::Base
acts_as_tree
end
# The actual test
class BugTest < Minitest::Test
def test_self_and_ancestors_eager_loading
root = Category.create!(name: 'root')
child = root.children.create!(name: 'child')
grandchild = child.children.create!(name: 'grandchild')
self_and_ancestors = Category.where(id: grandchild.id).includes(:self_and_ancestors).first!.self_and_ancestors
assert_equal([grandchild, child, root], self_and_ancestors)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment