按年份分组帖子 - Rails

时间:2013-07-08 23:25:00

标签: ruby-on-rails railscasts

我有一个名为“Shoes”的模型属于一个名为“History”的模型。我想在我的历史show.html.erb页面中显示所有鞋子,但我想按发布日期对它们进行分组。 (我有一个名为release的属性)。

我在Railscasts中使用这个例子:

shoes_controller

def index
  @shoes = Shoe.all(:order => 'release, name')
  @release_year = @shoes.group_by { |t| t.release.beginning_of_year }
end

鞋子index.html.erb视图

<% @release_year.each do |release, shoes| %>
  <% shoes.each do |shoe| %> 
     <%= shoe.name %>
  <% end %>
<% end %>

我希望能够这样做,但在我的历史 show.html页面上,我该如何做到这一点?

到目前为止我所拥有的:

历史记录show.html.erb

<% @history.shoes.each do |shoe| %> 
  <div class="shoe">
     <%= shoe.name %>
  </div>
<% end %>

感谢。

1 个答案:

答案 0 :(得分:0)

也许您可能想在鞋子视图中创建一个_shoes_by_year部分,然后渲染鞋子集合:

视图/鞋/ _shoe.html.erb

<div class=shoe>
    <%= shoe.name %>
</div>

视图/鞋/ _shoes_by_year.html.erb

<% shoes_by_year.each do |release_year, shoes| %>
   <div>
     <h3><%= release_year.year %></h3>
     <%= render 'shoes/shoe', collection: shoes %>
   </div>
<% end %>

histories_controller.rb

def show
  ...
  @shoes = @history.shoes.group_by { |shoe| shoe.release.at_beginning_of_year } 
end

/views/history/show.html.erb

...
<%= render 'shoes/shoes_by_year', object => @shoes %>