2013-05-29 46 views
0

我有表如何在Model Activrecord Rails中獲取樹?

id | name   |pid 
-------------------- 
1 | Cetegory1  | 0 
-------------------- 
2 | SubCatregory1 | 1 
-------------------- 
3 | SubCatregory2 | 1 
-------------------- 
4 | Cetegory2  | 0 
-------------------- 
5 | SubCatregory1 | 4 
-------------------- 
6 | SubCatregory2 | 4 

如何選擇樹Categoryes從該表中ActeveRecord Rails3中?

  • 類別1

- 子類別1

- 子類別2

  • 類別2

- 子類別1

- 子類別2

回答

0

在控制器:

# select category with condition pid = 0 
@categories = Category.where(:pid => 0) 

在視圖:

<ul> 
<% @categories.each do |c| %> 

    <li><%= c.name %><li> 
     # check if category not have subcategory 
     <% if Category.where(:pid => c.id).empty? %> 

     <% else %> 
     <dl> 
     # select subcategory with condition pid = c.id 
     <% Category.where(:pid => c.id).each do |sc| %> 
     <dd>-- <%= sc.name %></dd> 
     <% end %> 
     </dl> 
    <% end %> 
<% end %> 

結果:

  • 類別1

    - 子類別1

    - 子類別2

  • 類別2

  • 類別3

    - 子類別1

    - 子類別2

+0

非常感謝! – user2425138