This blog is part of our Rails 5 series.
Let's have a look at Rails view code that renders partial using a collection.
1# index.html.erb 2<%= render partial: 'todo', collection: @todos %> 3 4# _todo.html.erb 5<% cache todo do %> 6 <%= todo.name %> 7<% end %> 8
In the above case Rails will do one fetch from the cache for each todo.
Fetch is usually pretty fast with any caching solution, however, one fetch per todo can make the app slow.
Gem multi_fetch_fragments fixed this issue by using read_multi api provided by Rails.
In a single call to cache, this gem fetches all the cache fragments for a collection. The author of the gem saw 78% speed improvement by using this gem.
The features of this gem have been folded into Rails 5.
To get benefits of collection caching, just add cached: true as shown below.
1# index.html.erb 2<%= render partial: 'todo', collection: @todos, cached: true %> 3 4# _todo.html.erb 5<% cache todo do %> 6 <%= todo.name %> 7<% end %> 8
With cached: true present, Rails will use read_multi to the cache store instead of reading from it every partial.
Rails will also log cache hits in the logs as below.
1 Rendered collection of todos/_todo.html.erb [100 / 100 cache hits] (339.5ms)
Checkout the pull request to gain better understanding about how collection caching works.