简体   繁体   中英

Rails 3.1 Record Counter for Homepage

I had a quick question that's been bugging me. I'd like to place a counter on the homepage of my Rails 3.1.rc4 site to advertise how many micro-blogging posts are in the site's database. The problem is this number is going to grow to be huge over time and I don't want to have to use something like Post.find(:all).count . So this is where my question lies: is there an easy, cache-able (for let's say 8 hours), and non-resource intensive way to display a count of records in a database? I'm using ActiveRecord and Heroku hosting (Cedar Stack with no Varnish cache).

Thanks for your help!

Yeah, use Post.count and if you want to cache the result for 8 hours, do:

Rails.cache.fetch(:posts_count, :expires_in => 8.hours) do
  Post.count
end

Just use Post.count which does select count(id) from posts; in SQL.

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