views:

148

answers:

2

Hi everyone,

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 content

Item 2
Item 2 content

13th October 2009 Item 1
Item 3 content

How can I display that in view? (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

+2  A: 
items.group_by{ |item| item.created_at.to_date }
tig
+1  A: 

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.

KandadaBoggu
This seems to be just right, but how do I just compare the dates (day, month, year) without the time because if an item is posted just one minute or one second after the previous item, it will generate a new date header for it.
The call: 'item.date.to_date' prunes the time part from the 'datetime' field. So you should see the rows grouped by date rather than date-time.
KandadaBoggu
E.g.: Check this example:k = (1..10).collect{|i| Time.now + (i*3).hours}; p k; j = k.collect {|d| d.to_date}; p j Look at the two arrays printed. First one has the time part and the second one does not.
KandadaBoggu
Thanks!I think I've fixed that small little bug in that code, date should be:date = item.date.to_date in line #4It works perfectly now. Thanks :)