<%= link_to(submission.title, submission.url) %> |
<%= submission.url %> |
<%= submission.community.name %> |
<%= link_to("#{submission.comments.size} comments",
submission, class: 'btn btn-primary btn-xs') %>
|
<% end %>
```
---
# Submission Listing (with cache)
```erb
<% @submissions.each do |submission| %>
* <% cache(cache_key_for_submission(submission)) do %>
<%= link_to(submission.title, submission.url) %> |
<%= submission.url %> |
<%= submission.community.name %> |
<%= link_to("#{submission.comments.size} comments",
submission, class: 'btn btn-primary btn-xs') %>
|
* <% end %>
<% end %>
```
---
# Choosing a Cache Key
> How should we choose a cache key for a submission?
--
```ruby
module SubmissionHelper
def cache_key_for_submission(submission)
"submission/#{submission.id}"
end
end
```
> What are the weaknesses with the above approach?
--
* Invalidation will need to be explicit as the submission ID typically will
never be updated for an object.
* Explicitly invalidating cache items can easily make a mess of the code.
---
# Choosing a Better Cache Key
```ruby
module SubmissionHelper
def cache_key_for_submission(sub)
"submission/#{sub.id}/#{sub.updated_at}/#{sub.comments.count}"
end
end
```
With the above, a submission's fragment cache is invalidated anytime the
submission is updated (`updated_at` is automatically updated on change), or
when the number of comments associated with the submission changes.
_Note_: An Active Record model can be used directly as the key. It calls an
over-writable method `cache_key` on the model. By default that method returns a
key that "includes the model name, the id and finally the updated_at
timestamp".
Reference: