0

我的桌子是:

|  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. 我想以上述方式显示类别,前提是有任何产品并且我的产品模型如下所示:

当我单击链接时显示链接后,我计划显示所有相关产品。

谁能指导我如何显示有产品的类别?

4

1 回答 1

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 循环

于 2013-03-25T02:13:20.273 回答