I’m using devise, kaminari, and dalli(memcached).
I’ve just tried to implement caching when it’s loading http://example.com/communities?sort=popular
I tried to code just like below. However it seems cache storing is not working.
It looks like it’s still sending SQL every time it reloads the page…
What’s wrong?
Then if possible, I’d like to clear all the stored caches that contains the string “community_index_sort_by_” when after the user made or edited “Community” record.
config/environment/development.rb
...
config.consider_all_requests_local = true
config.action_controller.perform_caching = true
config.cache_store = :dalli_store
...
community_controller.rb
def index
@key = "community_index_sort_by_" + params[:sort].to_s + "_page_" + params[:page].to_s
if params[:sort] == 'popular'
unless Rails.cache.fetch(:controller => "communities", :action => "index", :action_suffix => @key)
@communities = Community.scoped.page(params[:page]).order("cached_votes_up DESC")
end
elsif params[:sort] == 'latest'
@communities = Community.scoped.page(params[:page]).order("created_at DESC")
end
end
I haven’t touched any in view files
Doesn’t the cache fragment get created in the view with a cache call?
In the view, don’t forget to include the params in the key, like the page offset:
In the controller:
This rails cast might be helpful.
http://railscasts.com/episodes/90-fragment-caching
For clearing the cache when updates are made rails sweepers are pretty helpful. You can define methods for model methods or controller actions. http://guides.rubyonrails.org/caching_with_rails.html#sweepers