Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails group by year problem

I have a Post model which includes a date_published. I want to display links on the index page to view all the posts of a certain year (a bit like where blogs have months you can view by)

The only way I can think of returning the years is by iterating over all of the posts and returning a unique array of the years that posts fall in. But this seems like a long way round. Does anyone have a better solution to this? Maybe it would be easier just creating new table so a Post belongs_to :year

Any suggestions?

like image 394
Cameron Avatar asked Dec 06 '22 05:12

Cameron


1 Answers

You don't have to iterate over all of them in your Ruby code. You can use the :group option with count:

>> Post.count(:all, :group => "Year(date_published)")
=> [["2005", 5], ["2006", 231], ["2007", 810], ["2009", 3]]

And then build the links from that.

like image 154
agentofuser Avatar answered Dec 22 '22 04:12

agentofuser