Q:

Rails 3 and memcaching an association

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 :)

A:

Creating a distinct method to hit the cache vs getting it fresh is not common from what I can tell. 
Most of the time, you'd just call a method that asks the cache all the time, since if you include an object in the cache-key, the updated_at field is used to build the key.
For your example now, the weird part is that you don't actually do anything with the Following model apart accessing its association. Therefore,  you should query directly on the Show model :
@recently_favorited_shows = Show.joins(:followings).order("followings.created_at DESC").uniq

Then in your view, loop on the shows. Only one query, no n+1
If you expect thousands of hits then, I'd just suggest to cache the result of @recently_favorited_shows and expire it every X minutes :
@recently_favorited_shows = cache_store.fetch('recently_favorited_shows', expires_in: 5.minutes){Show.joins(:followings).order("followings.created_at DESC").uniq}

On another note, here's a good write-up on cache usage on the view side if you want to do it some time: http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works
No joins solution
Edit : now, if you have gazillions of rows in followings table, here's what I'd do :

Create a field last_followed_at on the shows table, with an index on it
In Following.rb : belongs_to :show, touch: :last_followed_at. This way, as soon as you add a new entry in Following, it'll update the field on the shows table
Then, to get the latest followed shows, do :
@shows = Show.order("last_followed_at DESC").limit(10) # Fast query of course

