Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/closure_tree/association_setup.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,16 @@ def hash_tree(options = {})
class_name: _ct.hierarchy_class_name,
foreign_key: 'descendant_id'

has_many :self_and_ancestors, *_ct.has_many_order_without_option(order_by_generations),
has_many :self_and_ancestors,
through: :ancestor_hierarchies,
source: :ancestor

has_many :descendant_hierarchies, *_ct.has_many_order_without_option(order_by_generations),
class_name: _ct.hierarchy_class_name,
foreign_key: 'ancestor_id'

has_many :self_and_descendants, *_ct.has_many_order_with_option(order_by_generations),
descendants_order = _ct.order_option? ? _ct.has_many_order_with_option(order_by_generations) : []
has_many :self_and_descendants, *descendants_order,
through: :descendant_hierarchies,
source: :descendant
end
Expand Down
45 changes: 45 additions & 0 deletions test/closure_tree/preload_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# frozen_string_literal: true

require 'test_helper'

describe 'preloading tree associations' do
def build_chain(klass)
root = klass.create!(name: 'root')
mid = klass.create!(name: 'mid', parent: root)
leaf = klass.create!(name: 'leaf', parent: mid)
[root, mid, leaf]
end

[Tag, AdoptableTag, SecondaryTag, SecondaryAdoptableTag, MemoryTag, MemoryAdoptableTag].each do |klass|
describe klass.name do
%i[preload includes].each do |loader|
it "can #{loader} self_and_ancestors, ordered by generations" do
root, mid, leaf = build_chain(klass)

records = klass.public_send(loader, :self_and_ancestors).where(id: [root.id, leaf.id]).index_by(&:id)

assert records[leaf.id].association(:self_and_ancestors).loaded?
assert_equal [leaf, mid, root], records[leaf.id].self_and_ancestors.to_a
assert_equal [root], records[root.id].self_and_ancestors.to_a
assert_equal %w[root mid leaf], records[leaf.id].ancestry_path
end
end
end
end

[AdoptableTag, SecondaryAdoptableTag, MemoryAdoptableTag].each do |klass|
describe klass.name do
%i[preload includes].each do |loader|
it "can #{loader} self_and_descendants, ordered by generations" do
root, mid, leaf = build_chain(klass)

records = klass.public_send(loader, :self_and_descendants).where(id: [root.id, leaf.id]).index_by(&:id)

assert records[root.id].association(:self_and_descendants).loaded?
assert_equal [root, mid, leaf], records[root.id].self_and_descendants.to_a
assert_equal [leaf], records[leaf.id].self_and_descendants.to_a
end
end
end
end
end