I’ve just tried to implement caching when it’s loading example.com/communities?sort=popular
My code is just like this. However it seems caching is not working.
It looks like it’s still sending SQL every time it reloads…
What’s wrong?
Then When after the user made or edited “Community” record, I’d like to clear all the stored caches that contains the string “community_index_sort_by_”.
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 read_fragment(: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 in view
The code you’ve shown only attempts to read from the cache, it never stores anything to it. If you want to populate the cache if no value is found (e.g., on a cache miss) you can use
Rails.cache.fetchrather thanread_fragment.fetchwill return the cached value if one exists. Otherwise, if a block was passed then it will be run when a cache miss occurs and the return value will be stored in the cache. For instance, the relevant part of your code snippet would be something likeThe recommended approach for expiring cached data when an object is modified is to have the cache key include some piece of data that changes whenever the object is modified. This is commonly an
updated_attimestamp field, which ActiveRecord will automatically update when the object is saved. Theupdated_atfield also has the advantage of being automatically used as part of the cache key when the object is used directly as part of the cache key (e.g., a cache key of@communitywould result in a cache key of something likecommunities/1-20130116113736). This will typically require a small amount of restructuring to ensure that a relevant object is available to be used in the cache key. David Heinemeier Hansson discusses this in more detail. Step 5 in particular is most relevant to what I’ve mentioned here.