Can I paginate results by year?
I have a collection about 100 objects per year over 25 years. It would be nice to list them by year, per page开发者_如何学Python, so that it would be easier to drill down to a particular object. Is there a plugin or gem for paginating Rails collections by year, instead of a fixed number of items? Maybe even by month? Would it be possible to adapt will_paginate to do this?
EDIT:
ss = Services.all.group_by { |s| s.date_of_service.year }
This produces an ordered hash over which I can paginate by keys.
ss.keys.each { |k| p ss[k].count }
I don't think you will find such gem. And it shouldn't be that hard to implement a simple pagination system yourself using scopes.
I suppose you don't have a separate table for years. So to retrieve the full list of unique years, you should use group
method.
scope :years, lambda { select('year').group('year') }
scope :year, lambda { |year| where(:year => year) }
The other option would be what keruilin suggested. Use any pagination gem (I use kaminari) with the year
scope.
I'd implement general pagination using will_paginate. You'll have, for ex, 10-25 results per page no matter what year that you're viewing.
I'd then implement a second filtering mechanism by which you view results by year using some good ole AR / SQL magic. With my app, I used a drop-down to select the year, but you can user some other UI element.
I can't say for sure if will_paginate can help you with the by-year issue, but I wouldn't advise customizing it to fit your needs. Just creates a compatibility issue unless you monkeypatch.
精彩评论