ruby-on-railscachingactiverecordactionview

rails each_with_index cache


I'm trying to cache the following:

<% @equipment.sports.zip(@equipment.sport_equipments).each_with_index do |(sport, equipment), index| %>
   <% cache[cache_version_tool, equipment.cache_key, sport.cache_key, index] do %>
      <%= render 'sport', sport: sport, equipment: equipment, cached: true %>
   <% end %>
<% end %>

The block works fine with out cache but when I had it I receive:

ActionView::Template::Error (no block given (yield)):

How do I pass the each_with_index block to the cache?


Solution

  • It has nothing to do with the each_with_index. You are calling the cache method wrong.

    Your call of

    cache[cache_version_tool, equipment.cache_key, sport.cache_key, index] do
    

    gets translated to

    cache().[](cache_version_tool, equipment.cache_key, sport.cache_key, index) do
    

    cache() receives no arguments and does not receive a block. Inside it checks for cache with no arguments (which obviously does not exist) and then calls yield. Since cache() did not receive a block (the [] access did), then it raises an error of no block given (yield).

    Add a space between cache and [

    cache [cache_version_tool, equipment.cache_key, sport.cache_key, index] do
    

    Now it gets interpreted as

    cache([cache_version_tool, equipment.cache_key, sport.cache_key, index]) do
    

    And everything should work.

    Or better yet, add the parentheses for clarity.