开发者

Do to total the same elemen and to display t with paginating_find?

For example, Test Table

|id|name   |item_id|num|
|1 |apple  |1      |1  |
|2 |orenge |2      |1  |
|3 |开发者_高级运维orenge |2      |1  |
|4 |pear   |3      |1  |
|5 |apple  |1      |1  |
.....

In Controller,

@items = Test.find(:all, :page=>{:size=>20, :current=>params[:page]}) 

I use paginating_find plugin.

In view,

<% @items.each do |item| %>
<%=h item.name %> x <%= item.num %><br />
<% end %>
<%= link_to "before", {:page => @items.previous_page} if @items.previous_page? %>
<%= paginating_links(@items, :window_size => 20) %>
<%= link_to "next", {:page => @items.next_page} if @items.next_page? %> 

apple x 1
orenge x 1
orenge x 1
pear x 1
apple x 1

.....

How should I do to make it to the way below? (The structure of the table is not changed.)

apple x 2
orenge x 2
pear x 1
.....


You can use sum with the :group parameter to sum the count of all items which have the same name:

@items = Test.sum("count", :group => "name")

This will give you an OrderedHash of the form name => count. You can then iterate over that in the view.

However it seems strange that you even have multiple items with the same name, given that there is a count column. You should probably change the code that you use to create new items, so that it only creates a new item if one with that name does not already exist - otherwise it should increment the count of the existing item.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜