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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With