2012-08-08 65 views
0

我正在构建一个简单的博客应用程序,我想添加一个存档,人们可以点击一个月并显示当月的所有文章。这就像基于月份和年份的分组。例如,在轨道中分组记录

文章:

  • 2012年6月
  • 2011年5月

所以在约会时,点击它把你带到一个页面,并列出了一个月的全部文章。我怎样才能完成它?

+0

有什么问题呢? – madth3 2012-08-08 21:00:18

+0

如何完成它 – Uchenna 2012-08-08 21:36:15

回答

1

对于2012年7月:

require 'date' 

month = 7 
year = 2012 

start_date = Date.new(year,month,1) 
end_date = Date.new(year,month+1,1) - 1.day 

articles_in_july = Article.where(:created_at => start_date..end_date) 

您可以用上面的控制台测试。然而,在你的模型,你可能想:

def self.in_month(month,year) 
    start_date = Date.new(year,month,1) 
    end_date = Date.new(year,month+1,1) - 1.day 
    where(:created_at => start_date..end_date) 
end 

然后,您可以拨打:

Article.in_month(7,2012) 

或者,假设一个用户的has_many文章:

current_user.articles.in_month(7,2012) 
+1

你也可以这样做:'date = Date.new(year,month,1)'然后'where(:created_at => date..date.end_of_month)''。使它缩短一点。 – Mischa 2012-08-08 22:38:04

+0

很好。谢谢! – 2012-08-08 22:59:12

+0

答案很好,但我怎样才能在链接中通过月份和年份,假定列表项是链接标记。路线将如何。我一直试图这样做几乎整整一天,仍然不能通过一个月和一年的参数。 – Uchenna 2012-08-09 19:35:32