2009-08-28 80 views

回答

1

awesome_nested_set

order_column已經實施:在其列做排序,默認情況下它是 left_column_name。例如:acts_as_nested_set:order_column => :位置

closure_tree

如果你想要一個特定的順序,一個新的整數列添加到一個>遷移模型:

t.integer :sort_order 

並在您的模型中:

class OrderedTag < ActiveRecord::Base 
    has_closure_tree order: 'sort_order' 
end 
2

不幸的是,現在是不可能的。 在他們的班級中寫道:「由lft以外的列操縱不起作用」(lib/awesome_nested_set.rb)

+2

2和一些年後,這似乎仍然是這種情況? – gef 2013-01-24 18:07:17

+2

3年後呢? – Gediminas 2014-01-18 07:47:34

+2

對於它的價值,我能夠做到這一點的數據庫排序:@ item.children.except(:order).order(「your_sort_column」) – 2014-02-05 16:22:59

1

我確認@ kr00lix說了什麼。 我的方法來繞過這個問題:

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

但我同意,爲了避免無用的內存消耗,這將是更加美好直接設置才能在SQL命令。

5

這樣做將覆蓋數據庫排序:

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

例子:

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" 
0

我能夠用遞歸爲此在Rails的:

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

然後調用Model.root.add_self_and_children

但顯然這涉及一系列海量數據庫命中。

因此,如果有人比我更瞭解SQL遞歸,想將其轉換爲純SQL,那就太神奇了!

BTW,出於某種原因,以下,這將是在數據庫上有點親切,沒有工作:

def add_self_and_children 
    [self, children.order(:name).map{|c| c.add_self_and_children}].flatten 
end 
相關問題