glinda93
glinda93

Reputation: 8459

Rails low level caching is not working for active records

I'm using graphql for my rails api. And use redis for cache store.

In a graphql query, I'm using cache to optimize performance:

graphql/types/query_type.rb

field :labels, [Types::LabelType], null: false do
  description 'Get all food labels'
end

def labels
  Rails.cache.fetch("labels", expires_in: 24.hours) do
    Label.all
  end
end

10 labels are seeded in the database and when I test query in localhost:3000/graphiql, it shows 10 results correctly. However, if I delete a row manually in the database, it returns 9 records instead of cached 10 results.

Here is my environment configuration:

config/environments/development.rb

if Rails.root.join('tmp', 'caching-dev.txt').exist?
  config.action_controller.perform_caching = true
  config.cache_store = :redis_cache_store, { url: ENV.fetch("REDIS_URL_CACHING", "redis://localhost:6379/0") }
  config.public_file_server.headers = {
    'Cache-Control' => "public, max-age=#{2.days.to_i}"
  }
else
  config.action_controller.perform_caching = false
  config.cache_store = :null_store
end

I ran rails dev:cache and there is caching-dev.txt in tmp directory. What am I missing here?

Upvotes: 0

Views: 1685

Answers (1)

glinda93
glinda93

Reputation: 8459

I found similar questions and tried their answers. Suggested solutions are:

The first and second work correctly.

graphql/types/query_type.rb

def labels
  Rails.cache.fetch("labels", expires_in: 24.hours) do
    Label.all.load
  end
end

Tips: Run Rails.cache.clear in rails console whenever you change the cache block

The problem was that it is the block Label.all that was cached, not the results.

No matter how I change the block, it is already cached, so the results are NOT cached.

I ran Rails cache clear in rails console and it worked correctly.

Upvotes: 1

Related Questions