How to group content by date (Rails)

I am trying to combine content that belongs to the same date together for display, so that the date is only sent once and in chronological order.

Sort of:

October 14, 2009
Item 3
Level 3 Content

Clause 2
Contents of Clause 2

October 13, 2009 Item 1
Level 3 Content

How can I display this in a look? (Assume that @items is passed from a controller that contains all the elements)

I tried group_by, but I can't get it to work, as it seems to suit itself with the very cost of the day itself, not 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 real deployment, you can find it at http://political-watch.org

+3
source share
3 answers

1) Replace line 5 of the application / controllers / items_controller.rb with:

  @items = Item.all(:order => "date DESC")

2) Replace line 3-14 of the /views/items/index.html.erb application 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 use a database for sorting and a simple comparison for grouping.

PS: I don’t think it’s a good idea to name the columns of the database “date”. Some of the date databases have a keyword reserved.

+2
source
items.group_by{ |item| item.created_at.to_date }
+29
source

:

class AddIndexToItemsStartDate < ActiveRecord::Migration
  def change
    add_index :items, :start_date
  end
end

:

@items = Item.where("start_date >= ?", Time.zone.now.beginning_of_day)
@items_by_day = @items.group_by { |t| t.start_date.beginning_of_day }

:

<% @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 %>
0

Source: https://habr.com/ru/post/1720340/


All Articles