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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With