2012-03-15 19 views
1

我目前排序依據發佈日期的產品是這樣的:組和子組中的Rails

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

在控制器:

@products = Product.where('street_date > ?', Date.today).order('street_date ASC') 
    @product_months = @products.group_by { |t| t.street_date.beginning_of_month } 

產品,不過,也分爲三個sales_seaons,春天,夏天和秋天。我想進一步將這些物品分組到他們的海中,像這樣。 Year(年份)> Season(季節)> Product(產品),而不是Month(月份)> Product(產品),但對於我來說,分組證明有點複雜。有什麼想法嗎?

回答

3

Scopes是你的朋友。他們將類級方法添加到它們定義的模型中。關於它們的最好的部分是它們是可鏈接的。

有很多方法可以獲得您正在討論的分組,但以下是我要開始的。

class Product 
    # ... your code here 

    scope :by_sales_season, lambda {|season| where('sales_season = ?', season} 
    scope :by_year, lambda {|year| where('street_date >= ?' DateTime.now(year) } 

    # ... more of your code 
end 

然後在你的控制器,你可以:

@products = Product.by_year(2012).by_sales_season("spring")

當然,這不會返回到所有的產品遍及每年和/或每季,雖然範圍可以進行修改,以做這樣一件事,或者你可以循環相應的年份和季節。但是,如果你這樣做,而不是使用group_by方法,這是一個Enumerable方法,那麼當你只想要它的一個子集時,你不會冒險把整個結果集拉到內存中。

+0

謝謝,我做了一個小小的改動:'scope:by_year,lambda {| year | where(:street_date => DateTime.now(year).. DateTime.now(year).end_of_year)}' – Slick23 2012-03-15 17:19:42