Reputation: 607
I'm trying to cache a side_bar. Into it, there is two list of groups (1: favorite groups, 2: others_groups)
My caching aproach:
1.caching the two lists of groups into my model User
def cached_groups
Rails.cache.fetch([self, "groups"]) {groups.to_a}
end
def cached_favgroups
Rails.cache.fetch([self, "fav_groups"]) {fav_groups.to_a}
end
2.caching the entire list and below each of the group
<% cache 'cache_all_groups_fav' do %>
<% current_user.cached_favgroups.each do |group| %>
<% cache group do %>
<%= render 'groups/group', group: group %>
<% end %>
<% end %>
<% end %>
<% cache 'cache_all_groups' do %>
<% current_user.cached_groups.each do |group| %>
<% cache group do %>
<%= render 'groups/group', group: group %>
<% end %>
<% end %>
<% end %>
3.Expire the cache into my Groups/Controller
def favorit
FavoritGroup.where(group_id: @group.id).where(user_id: current_user.id).first_or_create
Group.where(group_id: @group.id).where(user_id: current_user.id).delete_all
expire_fragment('cache_all_groups_fav')
expire_fragment('cache_all_groups')
expire_fragment('cached_favgroups')
expire_fragment('cached_groups')
expire_fragment('group')
respond_to do |format|
format.html { redirect_back }
format.js { render 'groups/js/favorit' }
end
end
def unfavorit
FavoritGroup.where(group_id: @group.id).where(user_id: current_user.id).delete_all
Group.where(group_id: @group.id).where(user_id: current_user.id).first_or_create
expire_fragment('cache_all_groups_fav')
expire_fragment('cache_all_groups')
expire_fragment('cached_favgroups')
expire_fragment('cached_groups')
expire_fragment('group')
respond_to do |format|
format.html { redirect_back }
format.js { render 'groups/js/unfavorit' }
end
end
Note : To do that, I'm store_cache 'dally' Ruby2.4 (Rails 5.1.4)
Problem : The expire_fragment method is not working
Do you have any idea of what problem can append here ?
Do you do the same for you cache strategy ?
Upvotes: 3
Views: 75
Reputation: 3475
You should really be doing this caching in the front-end, with russian doll caching.
The cache will expire automatically when any of your group records are updated.
Upvotes: 1