<%= 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 will rarely, if
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 always updated), 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:
[http://guides.rubyonrails.org/caching_with_rails.html#fragment-caching](http://guides.rubyonrails.org/caching_with_rails.html#fragment-caching)
---
# More Fragment Caching
.left-column30[
Now we are caching a fragment for each submission.
> What else can we cache?
]
.right-column70[
![Submissions Index View](demo_submissions_index.png)
]
--
We can cache the entire submission listing!
---
# Community Listing (without cache)
```erb