简体   繁体   中英

Best way to join unique month and year from db in rails 3 ( or otherwise )

I am trying to figure out a nice way of doing this and thought maybe there is a nicer way in the newer Rails 3.0 ActiveRecord query.

I have a bunch of Posts that have a published_at field.

Now I want to present an Archive in the sidebar with all unique months and year that contains posts and display that archive. What's the best way to do this avoiding to heavy hits on the DB on every pageload? Suggestions?

You need a query along the lines of select distinct date_format(published_at, '%m %y'), count(id) from posts group by 1 . It's a trivial matter to convert this to AR syntax.

RE: pageload

Run the query for the archive and cache the result using either query caching or fragment caching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM