ruby on rails - Minimizing number of db-queries -


let's have post model.

in beginning of view need display total number of posts, typically

@posts.size 

later in view need display posts, typically

@posts.each |post|    end 

this results in 2 queries.

if had done queries in opposite order, had resulted in 1 single query (presumably utilizing cache).

is there "trick" can achieve (first) mentioned order 1 db query?

you can use example #fragment-caching

<% cache 'posts_size' %>   <%= @posts.size %> <% end %> 

then when post created can expire fragment

expire_fragment 'posts_size' 

Comments