Search code examples
ruby-on-railsrubycachingmemcachedfragment-caching

Memcached and Rails Fragment Caching Issue


When I have 2 views that fragment cache the same query BUT display them differently, there is only one fragment and they both display it the same way. Is there any way around this? For example...

#views/posts/list
    - cache(@posts) do
         - for p in @posts
              = p.title

#views/posts/list_with_images
    - cache(@posts) do
         - for p in @posts
              = p.title
              = p.content
              = image_tag(p.image_url)

#controllers/posts_controller
     def list
        ...
        @posts = Post.all
     end

     def list_with_images
        ...
        @posts = Post.all
     end

Solution

  • You have to use a unique cache key. If you simple pass in an object it calls the cache_key method on it to determine the key. If you pass in an array of objects, cache will generate a key by joining the cache keys of all the elements of the array. You can use this to fix your problem through:

    #views/posts/list
        - cache([:list, @posts]) do
             - for p in @posts
                  = p.title
    
    #views/posts/list_with_images
        - cache([:list_with_images, @posts]) do
             - for p in @posts
                  = p.title
                  = p.content
                  = image_tag(p.image_url)