From 009aafc4c570b2652bd2985d9449221d482972ea Mon Sep 17 00:00:00 2001 From: Mitsuru Hayasaka Date: Wed, 29 Mar 2023 05:06:38 +0900 Subject: [PATCH] Fixes `.sort_by_ancestry` with custom `ancestry_column` --- lib/ancestry/class_methods.rb | 2 +- test/concerns/sort_by_ancestry_test.rb | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/ancestry/class_methods.rb b/lib/ancestry/class_methods.rb index cd01ff3c..cf41c9e1 100644 --- a/lib/ancestry/class_methods.rb +++ b/lib/ancestry/class_methods.rb @@ -98,7 +98,7 @@ def sort_by_ancestry(nodes, &block) unless arranged presorted_nodes = nodes.sort do |a, b| - rank = (a.ancestry || ' ') <=> (b.ancestry || ' ') + rank = (a.public_send(ancestry_column) || ' ') <=> (b.public_send(ancestry_column) || ' ') rank = yield(a, b) if rank == 0 && block_given? rank end diff --git a/test/concerns/sort_by_ancestry_test.rb b/test/concerns/sort_by_ancestry_test.rb index 768d2809..be9c8692 100644 --- a/test/concerns/sort_by_ancestry_test.rb +++ b/test/concerns/sort_by_ancestry_test.rb @@ -233,4 +233,17 @@ def test_sort_by_ancestry_with_block_paginated_missing_parents_and_children end end end + + def test_sort_by_ancestry_with_ancestry_column + AncestryTestDatabase.with_model :ancestry_column => :t1, :extra_columns => {:rank => :integer} do |model| + _, n2, n3, n4, n5, _ = build_ranked_tree(model) + + records = model.sort_by_ancestry(model.all.ordered_by_ancestry_and(:rank).offset(1).take(4), &RANK_SORT) + if CORRECT + assert_equal [n3, n2, n4, n5].map(&:id), records.map(&:id) + else + assert_equal [n2, n4, n5, n3].map(&:id), records.map(&:id) + end + end + end end