I’m currently sorting products based on release date this way:
<% @product_months.each do |month, products| %>
<h2><%= month.strftime("%B %Y") %></h2>
<% products.each do |product| %>
<p><b><%= product.title %></b> on <%= product.street_date.to_date.to_s(:long) %></p>
<% end %>
<% end %>
In the controller:
@products = Product.where('street_date > ?', Date.today).order('street_date ASC')
@product_months = @products.group_by { |t| t.street_date.beginning_of_month }
Products, though, are also grouped into three sales_seaons, spring, summer and fall. I’d like to further group the items into their seaons, like this. Year > Season > Product, instead of Month > Product, but the grouping is proving a little too complicated for me to get. Any thoughts?
Scopes are your friend. They add class level methods to the model they’re defined in. The best part about them is that they’re chainable.
There are many ways to get the groupings you’re talking about but here’s what I would start with.
Then in your controller you could:
@products = Product.by_year(2012).by_sales_season("spring")Of course this will not return to all products across every year and/or every season, though the scopes could be modified to do such a thing, or you could loop over the years and seasons accordingly. However, if you do it this way versus using the group_by method which is an
Enumerablemethod then you don’t risk pulling the entire result set into memory when you only want a subset of it.