Following.rb
belongs_to :show
def cached_show
Rails.cache.fetch([self, :show]) do
show
end
end
View:
<% @recently_favorited.each do |following| %>
<li>
<%= link_to "#{following.cached_show.name}", show_path(:permalink => following.cached_show.permalink) %> <span><%= "(#{pluralize(following.cached_show.followers, "follower")})" %></span>
</li>
<% end %>
Result in the console:
Cache read: followings/632770-20120929132253/show
Cache generate: followings/632770-20120929132253/show
Show Load (0.7ms) SELECT `shows`.* FROM `shows`WHERE `shows`.`id` = 617 LIMIT 1
Cache write: followings/632770-20120929132253/show
Cache read: followings/632770-20120929132253/show
Cache fetch_hit: followings/632770-20120929132253/show
Cache read: followings/632770-20120929132253/show
Cache fetch_hit: followings/632770-20120929132253/show
Question:
Is this even a "correct" implementation of fetching/caching an association?
And what about performance?
In some views (as in the example) it will hit the cache 3 times per loop. In my case I'm looping 10 items in the footer, so it will make 30 hits on every request. Is this fine, or will a single n+1 query per loop be better?
Advise and general best practices appreciated :)