Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fragment caching in Rails per user

I have page which list all events. But listing of event depends on whether user is admin or not. If I use fragment caching on the page where I iterate through model object on view, it will cache all events for admin.

Can it get served from cache to another user who is not admin? If yes, how I can use fragment caching for non-admin and admin user.

like image 428
Ajay Avatar asked Jan 29 '14 06:01

Ajay


3 Answers

Do something like the following with the fragment cache key:

<% cache [current_user.role, :events] do %>
  <b>All the Events based on the Current User's Role</b>
  <%= render events %>
<% end %>

http://api.rubyonrails.org/classes/ActionView/Helpers/CacheHelper.html#method-i-cache

You can pass any number of items in the name argument of the cache method to cater the cache to your circumstance.

like image 81
omarvelous Avatar answered Oct 02 '22 15:10

omarvelous


You probably want to do something like this:

<%= cache_unless admin?, project do %>
  <b>All the topics on this project</b>
  <%= render project.topics %>
<% end %>

Example lifted from the Rails docs: http://api.rubyonrails.org/classes/ActionView/Helpers/CacheHelper.html#method-i-cache_unless

like image 20
Eugene Otto Avatar answered Oct 02 '22 15:10

Eugene Otto


In your controller:

class ApplicationController < ActionController::Base

    fragment_cache_key do
      current_user.role
    end

#...

This will be used by Rails's fragment caching and added to the list of fragment_cache_keys when it constructs the cache key. So you'll just automagically get unique cache keys for each user role (or use anything you like in there) whenever you use any of Rails's fragment caching.

like image 20
smathy Avatar answered Oct 02 '22 15:10

smathy