2012-07-20 266 views
2

選擇親子遞歸我有一個表稱爲類別中,表結構及數據Rails 3中的ActiveRecord從單桌

id | parent_id | name 
------------------------ 
1 | 0   | Computers // parent 
2 | 0   | TV   // parent 
4 | 1   | Motherboards // child - to - id(1) 
5 | 4   | Mercury 
6 | 5   | Mecrury XXX 
7 | 6   | Mecrury YYY 

(其中PARENT_ID是另一行的ID

顯示如何使用Rails3 Activerecord查詢界面得到父/子結果。 (或任何其他解決方案)。

如果我搜索計算機我怎麼能得到所有的孩子 - >超級孩子在該父類別下。

Example Result will - Computers -> Motherboards -> Mercury XXX -> Mercury YYY 

謝謝

回答

1

你應該看看awesome nested set寶石。

它允許你調用這樣的事情讓所有的子節點:

Node.root.self_and_descendants 

ancestry似乎一樣好,雖然我沒有用它自己。

這兩個gem都需要遷移你的數據,但它更好,因爲只使用parent_id來導航子節點並不是最有效的。