在Rails中显示数据库值?

时间:2013-03-25 01:48:41

标签: ruby-on-rails ruby

我的表是:

|  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。我想以上述方式显示类别,仅当有任何产品且我的产品型号如下所示:

点击链接后显示链接,我打算显示所有相关产品。

有人可以指导我如何显示有产品的类别吗?

1 个答案:

答案 0 :(得分:1)

您可以使用Enumerable#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的块会被评估,并且每个评估为相同值的记录会在哈希键下组合在一起,您可以使用.each

进行循环。