I'm currently testing the caches in my app (Dalli gem). And a weird thing is happening. I'm caching a list related with the current_user. But when I test the app with different account (with different browsers), the caches are mixed.
For example: I run an action which change the caches of User1 , and those caches are applied to the account of User2.
So I would like to know if this problem is happening only because I'm doing it on development on the same computer, or if I should improve my cache system ?
Note: I've skip the digest to make it work, I'm not really sure of their needs. So i'm not really sure if that can be the starting point of my problem.
I share my code if you want more details of what I'm doing.
My code :
User (model):
class User < ApplicationRecord
has_many :users_group, dependent: :destroy
has_many :groups, through: :users_group
has_many :favorit_groups, dependent: :destroy
has_many :fav_groups, through: :favorit_groups, class_name: "Group", source: :group
def cached_favgroups
Rails.cache.fetch([self, "fav_groups"]) {fav_groups.to_a}
end
def cached_groups
Rails.cache.fetch([self, "groups"]) {groups.to_a}
end
View (sidenav):
<li class="list_groups_favorit">
<% cache 'cache_groups_fav_all', skip_digest: true do %>
<% current_user.cached_favgroups.each do |group| %>
<% cache group, skip_digest: true do %>
<%= render 'groups/group', group: group%>
<% end %>
<% end %>
<% end %>
</li>
<li class="list_groups">
<% cache 'cache_groups_all', skip_digest: true do %>
<% current_user.cached_groups.each do |group| %>
<% cache group, skip_digest: true do %>
<%= render 'groups/group', group: group%>
<% end %>
<% end %>
<% end %>
</li>
GroupController :
def favorit
FavoritGroup.where(group_id: @group.id).where(user_id: current_user.id).first_or_create
# Cache
Rails.cache.delete(current_user.cache_key+"/fav_groups")
Rails.cache.delete(current_user.cache_key+"/groups")
expire_fragment('cache_groups_fav_all')
expire_fragment('cache_groups_all')
expire_fragment(@group)
# Cache
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
# Cache
Rails.cache.delete(current_user.cache_key+"/fav_groups")
Rails.cache.delete(current_user.cache_key+"/groups")
expire_fragment('cache_groups_fav_all')
expire_fragment('cache_groups_all')
expire_fragment(@group)
# Cache
respond_to do |format|
format.html { redirect_back }
format.js { render 'groups/js/unfavorit' }
end
end