Skip to content

Commit ae78bc2

Browse files
committed
Fixes issue where ancestors would be returned in natural order instead of their actual order. Fixes benedikt#39
1 parent 6553e06 commit ae78bc2

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

lib/mongoid/tree.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ module Tree
103103
end
104104

105105
##
106-
# This module implements class methods that will be available
106+
# This module implements class methods that will be available
107107
# on the document that includes Mongoid::Tree
108108
module ClassMethods
109109

@@ -213,7 +213,7 @@ def leaves
213213
# @note Generated by Mongoid
214214
#
215215
# @param [Mongoid::Tree] document
216-
216+
217217
##
218218
# @!method parent_ids
219219
# Returns a list of the document's parent_ids, starting with the root node.
@@ -272,7 +272,7 @@ def root
272272
#
273273
# @return [Mongoid::Criteria] Mongoid criteria to retrieve the documents ancestors
274274
def ancestors
275-
base_class.where(:_id.in => parent_ids)
275+
base_class.or(parent_ids.map { |id| { :_id => id } })
276276
end
277277

278278
##

spec/mongoid/tree_spec.rb

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -270,8 +270,24 @@
270270
end
271271

272272
describe 'ancestors' do
273-
it "#ancestors should return the documents ancestors" do
274-
node(:subchild).ancestors.to_a.should == [node(:root), node(:child)]
273+
describe '#ancestors' do
274+
it "should return the documents ancestors" do
275+
node(:subchild).ancestors.to_a.should == [node(:root), node(:child)]
276+
end
277+
278+
it "should return the ancestors in correct order even after rearranging" do
279+
setup_tree <<-ENDTREE
280+
- root:
281+
- child:
282+
- subchild
283+
ENDTREE
284+
285+
child = node(:child); child.parent = nil; child.save!
286+
root = node(:root); root.parent = node(:child); root.save!
287+
subchild = node(:subchild); subchild.parent = root; subchild.save!
288+
289+
subchild.ancestors.to_a.should == [child, root]
290+
end
275291
end
276292

277293
it "#ancestors_and_self should return the documents ancestors and itself" do

0 commit comments

Comments
 (0)