Amazing nested preset order

Im using a cool nested set for rubies on rails. How do I sort, for example: a column of names or something else?

Currently showing the tree as

A - C - B 

I want to like it

 A - B - C 
+2
source share
5 answers

Already implemented in awesome_nested_set

order_column: in which column to sort, the default is left_column_name. Example: act_as_nested_set: order_column =>: Position

and closure_tree

If you need a specific order, add a new integer column to your model in> migration:

 t.integer :sort_order 

and in your model:

 class OrderedTag < ActiveRecord::Base has_closure_tree order: 'sort_order' end 
+1
source

Doing this overrides the sorting of the database:

 @item.children.except(:order).order("your_sort_column") 

Example:

 organization.self_and_descendants.to_sql => "SELECT `organizations`.* FROM `organizations` WHERE (`organizations`.`lft` >= 1 AND `organizations`.`lft` < 54) ORDER BY `organizations`.`lft`" organization.self_and_descendants.except(:order).order("organization_nm").to_sql => "SELECT `organizations`.* FROM `organizations` WHERE (`organizations`.`lft` >= 1 AND `organizations`.`lft` < 54) ORDER BY organization_nm" 
+5
source

Unfortunately, this is not possible now. It says in its class that "odering with a column other than lft does not work" (lib / awesome_nested_set.rb)

+3
source

I confirm what @ kr00lix said. My way around this problem is:

 @item_children = @item.children @item_children = @item_children.sort_by!(&:your_sort_column) 

But I agree that in order to avoid useless memory consumption, it would be much better to set the order in the SQL command directly.

+1
source

I was able to do this in Rails with recursion:

 def add_self_and_children [self, children.sort_by{|e| e.name}.map{|c| c.add_self_and_children}].flatten end 

Then call Model.root.add_self_and_children .

But, obviously, this includes a number of massive database calls.

So, if someone knows more about SQL recursion than I want to convert this to pure SQL, that would be magical!

By the way, for some reason, the following, which would be slightly better in the database, did not work:

 def add_self_and_children [self, children.order(:name).map{|c| c.add_self_and_children}].flatten end 
0
source

Source: https://habr.com/ru/post/1332865/


All Articles