How do I group content according to date (Rails)
I'm trying to group contents that belong on a same date together for display, such that the date only gets posted once and in chronological order.
Something like:
14th October 2009
Item 3 Item 3 contentItem 2
Item 2 content13th October 2009 Item 1
Item 3 contentHow can I display that in v开发者_Python百科iew? (Assume that @items is being passed from the controller, which contains all the items)
I've tried group_by, but I can't get it to work as it seems to be arranging itself by the value of the day itself rather than together with the month.
The code in question: http://github.com/davidchua/Political-Watch/blob/master/app/views/items/index.html.erb
To see the problem in a live deployment, its at http://political-watch.org
items.group_by{ |item| item.created_at.to_date }
1) Replace the line 5 of app/controllers/items_controller.rb with:
@items = Item.all(:order => "date DESC")
2) Replace line 3-14 of app/views/items/index.html.erb with:
<% date = 1.day.from_now(@items.first.date.to_date) rescue nil # increment the day
@items.each do |item|
if date > item.date.to_date
date = item.date.to_date %>
<div style="background: #81BEF7;margin-top: 5px; margin-bottom: 5px;" class="rounded"><b><span style="padding: 5px"><%=h date %></span></b></div>
<%end%>
<p>
<i><%=h item.time %> - </i>
<%= link_to "#{item.title}", item.link %><br>
<a href="/items/<%=item.id%>"><span class="subtext" style="margin-left: 55px">by <%= item.user.username %> | <%=item.comments.count%> comments </span></a>
</p>
<% end # end for items_each%>
In this approach you are using the DB for sorting and a simple comparison for grouping.
PS: I don't think it is a good idea to name your database columns as 'date'. In some of the databases 'date' is a reserved keyword.
Add the following migration:
class AddIndexToItemsStartDate < ActiveRecord::Migration
def change
add_index :items, :start_date
end
end
Controller:
@items = Item.where("start_date >= ?", Time.zone.now.beginning_of_day)
@items_by_day = @items.group_by { |t| t.start_date.beginning_of_day }
View with nice display:
<% @items_by_day.sort.each do |day, items| %>
<h2><%= day.strftime("%d %B %Y") %></h2>
<table class="table table-striped">
<thead>
<tr>
<th>Item</th>
<th></th>
</tr>
</thead>
<% for item in items %>
<tbody>
<tr>
<td><%= item.item_id %></td>
<td><%= link_to 'Delete', item, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
</tbody>
<% end %>
</table>
<% end %>
精彩评论