2013-03-25 46 views
0

我的表是:在Rails中顯示數據庫值?

| 1 | Electronics  | Cameras   
| 2 | Electronics  | Computers  
| 3 | Electronics  | Mobile Phone  
| 4 | Electronics  | Sound & Vision 
| 5 | Clothes   | womens clothing 
| 7 | Clothes   | women shoes  
| 8 | Clothes   | women hand bags 
| 9 | Clothes   | Mens clothing 
| 10 | Clothes   | Kids clothing 

我想獲得一個鏈接顯示我的索引頁上是這樣的:

**Electronics** 
Computers 
Mobile Phone 
Sound & Vision 
**Clothes** 
womens clothing 
women shoes 
Mens clothing 

我如何做到這一點?

我的模式是這樣的:

class Category < ActiveRecord::Base 
    has_many :products 
    attr_accessible :division,:subdivision 
    end 


class Product < ActiveRecord::Base 
     has_many :photos,:dependent => :destroy 
     has_many :line_items, :through => :product_id 
     belongs_to :merchant 
     belongs_to :category 
     attr_accessor :quantity 
     accepts_nested_attributes_for :photos, :line_items 

分類表是家長和產品具有category_id。我想以上述方式顯示類別,只有當有任何產品和我的產品型號如下所示時:

鏈接顯示,當我點擊鏈接時,我打算顯示所有相關產品。

任何人都可以指導我如何顯示有產品的類別?

+0

這是一個視圖問題。你能告訴我們你的視圖/控制器文件是什麼樣子嗎? – jason328 2013-03-25 02:05:32

+0

我還沒有創建視圖。但在我的類別控制器看起來像這樣,我看到我的show.html.erb中的數據。但我不知道如何顯示它在我的主頁index.html.erb pageclass CategoryController user2067515 2013-03-25 02:08:28

回答

1

您可以用可枚舉#GROUP_BY

<% Category.all.group_by{|c| c.division }.each do |division, subdivisions| %> 
    <%= "**#{division}**" %><br> 
    <% subdivisions.each do |subdivision| %> 
    <%= subdivsion %><br> 
    <% end %> 
<% end %> 

http://railscasts.com/episodes/29-group-by-month?view=asciicast

傳遞給GROUP_BY塊被評估,並且每一個計算結果爲相同的值下的哈希鍵被組合在一起,記錄輕鬆地做到這一點,你可以循環使用。每個

+4

您可能想要添加一個解釋代碼在做什麼,而不是隻有一個代碼的答案。按原樣,它被標記爲低質量(供審覈),儘管它可能會給OP一個解決方案。 – 2013-03-25 02:36:24

+0

+ 1 @ LynnCrumbling。 SO想要解釋爲什麼代碼能夠工作,而不僅僅是代碼。這是給某人一條魚或教他們如何釣魚的區別。 – 2013-03-25 02:55:04

+0

+1非常好:) – 2013-03-25 13:52:36