2016-08-16 138 views
1

您好我正在使用rails和bootstrap創建一個站點,其中有一個列表組填充了帖子。我希望能夠爲每個單獨的日子分配單獨的列表組。按創建日期分隔列表

例如在現階段,我有:

<ul class="list-group"> 
    <% @posts.each do |post| %> 
    <li class="list-group-item">User has... <%= post.title%> </h2 class="pull-r"> <span class="pull-right"><%=link_to 'View', post%></span></li> 
    <%end%> 
</ul> 

這給我:

enter image description here

但是我希望它看起來像:

enter image description here

(儘管顯然與不同的p每天發送)

但是我遇到了麻煩,任何幫助都會很大。

+0

示例代碼創建的記錄數組僅顯示用於在列表組中生成項目的循環。你有什麼企圖循環和創建每個日期的列表組? –

+0

我對軌道非常陌生,所以我不確定從哪裏開始。 – user2320239

回答

1

組記錄日期

# change the .all with your condition 
@posts = Post.all.group_by(&:created_at) 

集團通過將返回一個散列結果,其中日期將是關鍵和值將與在該日期

<ul class="list-group"> 
    <% @posts.each do |date, posts| %> 
    <li> 
     <h3><%= date.to_date.to_s %></h3> 
     <ul> 
     <% posts.each do |post| %> 
      <li class="list-group-item"> 
      User has... <%= post.title%> </h2 class="pull-r"> 
      <span class="pull-right"><%=link_to 'View', post%></span>  
      </li> 
     <%end%> 
    </ul> 
    </li> 
    <%end%> 
</ul> 
+0

感謝您的回覆,但是如果我這樣做,我得到一個錯誤未定義的方法'標題'爲# user2320239

+0

它現在正在工作,但它爲每個帖子添加一個日期,而不是按天分組 – user2320239