0

I have model called "Shoes" that belongs to the a model called "History". I want to show all of the shoes in my History show.html.erb page, but I want to group them by their release date. (I have an attribute called release for that).

I'm using this example from Railscasts:

shoes_controller

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

Shoes index.html.erb view

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

I want to be able to do this but on my History show.html page, how can i accomplish this?

What I have so far:

History show.html.erb

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

Thanks.

4

1 回答 1

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

history_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 %>
于 2013-07-09T00:03:54.853 回答