File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -90,6 +90,15 @@ def with_ancestor(*ancestors)
9090 _ct . scope_with_order ( scope )
9191 end
9292
93+ def with_descendant ( *descendants )
94+ descendant_ids = descendants . map { |ea | ea . is_a? ( ActiveRecord ::Base ) ? ea . _ct_id : ea }
95+ scope = descendant_ids . blank? ? all : joins ( :descendant_hierarchies ) .
96+ where ( "#{ _ct . hierarchy_table_name } .descendant_id" => descendant_ids ) .
97+ where ( "#{ _ct . hierarchy_table_name } .generations > 0" ) .
98+ readonly ( false )
99+ _ct . scope_with_order ( scope )
100+ end
101+
93102 def find_all_by_generation ( generation_level )
94103 s = joins ( <<-SQL . strip_heredoc )
95104 INNER JOIN (
Original file line number Diff line number Diff line change @@ -417,6 +417,35 @@ def assert_parent_and_children
417417 end
418418 end
419419
420+ context 'with_descendant' do
421+ it 'works with no rows' do
422+ expect ( tag_class . with_descendant . to_a ) . to be_empty
423+ end
424+
425+ it 'finds only parents' do
426+ c = tag_class . find_or_create_by_path %w( A B C )
427+ a , b = c . parent . parent , c . parent
428+ spurious_tags = tag_class . find_or_create_by_path %w( D E )
429+ expect ( tag_class . with_descendant ( c ) . to_a ) . to eq ( [ a , b ] )
430+ end
431+
432+ it 'limits subsequent where clauses' do
433+ ac1 = tag_class . create ( name : 'A' )
434+ ac2 = tag_class . create ( name : 'A' )
435+
436+ c1 = tag_class . find_or_create_by_path %w( B C1 )
437+ ac1 . children << c1 . parent
438+
439+ c2 = tag_class . find_or_create_by_path %w( B C2 )
440+ ac2 . children << c2 . parent
441+
442+ # different paths!
443+ expect ( ac1 ) . not_to eq ( ac2 )
444+ expect ( tag_class . where ( :name => 'A' ) . to_a ) . to match_array ( [ ac1 , ac2 ] )
445+ expect ( tag_class . with_descendant ( c1 ) . where ( :name => 'A' ) . to_a ) . to eq ( [ ac1 ] )
446+ end
447+ end
448+
420449 context 'paths' do
421450 context 'with grandchild' do
422451 before do
You can’t perform that action at this time.
0 commit comments