Search code examples
ruby-on-rails-4activerecordmemcacheddalli

Why is the database still being hit even after memcached stores the result?


I am making a few basic queries with active record and attempting to store the result in memcached using the dalli gem.

I have the following code:

@page = Rails.cache.fetch 'pages/index' do
  Page.find_by_name('index')
end

@grid_items = Rails.cache.fetch 'pages/index/grid_items' do
  @page.grid_items
end

Storing and retrieving works fine for the 'pages/index', but the 'pages/index/grid_items' still results in a database query. The following output from my localhost shows this:

Cache read: pages/index
Cache fetch_hit: pages/index
Cache read: pages/index/grid_items
Cache fetch_hit: pages/index/grid_items
GridItem Load (0.7ms)  SELECT "grid_items".* FROM "grid_items" WHERE (status = 't') AND (page_id = 1)  ORDER BY "grid_items"."position" ASC

I have tried using "includes" instead of "joins", without luck. I have also checked the result of Rails.cache.fetch in the console and it returns the correct data.


Solution

  • The answer was that I needed to make sure that ActiveRecord actually hit the database. I was caching a query object, and not the results.

    To trigger a database call I ended up using this, to cast the query to an array:

    @grid_items = Rails.cache.fetch 'pages/index/grid_items' do
      @page.grid_items.live.to_a
    end