Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I recently read an article on the 37Signals blog and I'm left wondering how it is that they get the cache key.

It's all well and good having a cache key that includes the object's timestamp (this means that when you update the object the cache will be invalidated); but how do you then use the cache key in a template without causing a DB hit for the very object that you are trying to fetch from the cache.

Specifically, how does this affect One to Many relations where you are rendering a Post's Comments for example.

Example in Django:

{% for comment in post.comments.all %}
   {% cache comment.pk comment.modified %}
     <p>{{ post.body }}</p>
   {% endcache %}
{% endfor %}

Is caching in Rails different to just requests to memcached for example (I know that they convert your cache key to something different). Do they also cache the cache key?

share|improve this question
Take a look at rossp.org/blog/2012/feb/29/fragment-caching for a Django example! –  vdboor Mar 8 '12 at 16:10
I already had a look at that and that seems to suffer from exactly the same problem. The data he's trying to cache is required in order to access the cache. The only thing he seems to be saving on is in the inner expensive operation which is unlike most use cases for this type of caching. –  Dominic Santos Mar 13 '12 at 9:11
That's true, an also happens with the 37signals code, it is focussed on the rendering code. The trick is to cache the whole list in another container too, or cache the retrieval of the object elsewhere. –  vdboor Mar 13 '12 at 10:29
Actually their caching strategy seems a little bit more educated. I recommend this article as well: 37signals.com/svn/posts/… –  JensG Nov 25 '13 at 17:35
add comment

1 Answer

Your example is good if it needs some data retrieval or processing for each comment. If you just take body and display it - cache will be useless. But you can cache all comments tree (including {% for %}). It this case you need to invalidate it with every added comment, so you can put last comment timestamp or comments count somewhere into Post and build comments cache key with it. If you prefer more normalized data, and use comments on only one page, you can just clear a cache key on comment save.

For me, saving comments count in Post looks good enough (if you don't allow to delete and edit comments) - you have a value to show anywhere with the Post and a key for caching.

share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.