Search Rails Blog Archive by Date

I make ruby ​​on the rails archive blog. The backend works fine, but the year is displayed separately, as you can see in the image below.

enter image description here

As you can see in the picture above, come separately. But if I give the blog in the same month, it works fine, as you can see in the month august 2014(accident, policy), but not for 2014.

This is the controller

@posts_by_month = Cutting.find(:all, :order => "date DESC").group_by { |post| post.date.beginning_of_month }

view

<div class="easy-tree" style="float:left;width:300px;background: #aaaaaa;">
   <%# @post_months.sort.reverse.each do |month, posts| %>
    <%@posts_by_month.each do |month, posts|%>
    <ul>
      <li><%=h month.strftime("%G")%>
        <ul>
          <li><%=h month.strftime("%B") %>
              <!--li ><%=h month.strftime %>-->
            <ul>
            <% for post in posts %>
              <li style="background: #aaaaaa;"class="getid" name ="<%=post.id%>"><%=h link_to post.subject%></li>
            <% end %>
                </ul>
              <!--/li-->            
          </li>
        </ul>
      </li>
    </ul>
    <% end %>
  </div>

I use easy-tree to get ui for

+4
source share
2 answers

try it

 @posts = Cutting.all(:select => "id, subject, date, created_at", :order => "date DESC")
 @post_months = @posts.group_by { |t| t.created_at.beginning_of_year }

And according to your ideas

<div class="easy-tree" style="float:left;width:300px;background: #aaaaaa;">
    <% @post_months.sort.reverse.each do |year, postss| %>
    <ul>
      <li><%=h year.strftime("%G")%>
        <% postss.group_by { |t| t.created_at.beginning_of_month }.each do |month, posts| %>
        <ul>
          <li><%=h month.strftime("%B") %>  
            <ul>
            <% for post in posts %>
              <li style="background: #aaaaaa;" class="getid" name ="<%=post.id%>"><%=h link_to post.subject %></li>
            <% end %>
                </ul>
           </li>
        </ul>
        <% end %>
      </li>
    </ul>
    <% end %>
  </div>

Output:

output

+2
source

, . , . year/month , , ( ).

@posts_by_month.debug , , . ,

-

Fix

year, month. , , , year, month, :

@posts_by_month = Post.all.order(date: :desc).group("year(created_at)").group("month(created_at)")

.group

0

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


All Articles