Caching Russian doll and permissions based link as a fragment

I have a view that uses Russian doll caching where the entire set of items is cached and each item in the collection is cached separately in that cache.

However, each item in the collection must show edit / delete links based on the current user permissions granted through CanCan. This way, User A will see edit / delete links next to their own posts, but not next to User B's posts.

Okay, whenever a post is created by user A, it is cached with the appropriate edit / delete links as she needs to have them visible based on her rights. But when user B browses the collection, he was serving a "Custom cache" message as well as edit / delete links that he shouldn't see. The provided CanCan prevents these edit / delete actions, but the links are still present.

Anyway, around creating separate caches based on current_user.id and preventing gobs from having versions of (almost) identical cached content?

+3


source to share


1 answer


Anyway, around creating separate caches based on current_user.id and preventing gobs from having versions of (almost) identical cached content?

Instead of including the user ID in the key cache, you can enable user permissions. This will still have duplicate copies of the content, but will scale according to your resolution model, not the number of users. Therefore, instead of the typical:

<% cache("posts/all-#{Post.maximum(:updated_at).try(:to_i)}") do %>
...
<% end %>

      



you can create a cache key, for example (assuming it current_user

returns an authenticated user) and you only care about editing and reading:

<% cache("posts/all-#{Post.maximum(:updated_at).try(:to_i)}-#{current_user.can?(:edit, Post) ? :edit : :read}") do %>
...
<% end %>

      

Please note that the cache key generation probably needs to be retrieved for a separate class / helper method.

+1


source







All Articles