Rails 4 - low level caching on demand

I follow the low-level caching guide found on the Heroku website . Copying their example is almost verbatim, here is my method:

def Trip.test_low_level
  Rails.cache.fetch("test_destinations", expires_in: 12.hours) do
    Trip.all.joins(:destinations).where("destinations.id = ?", 382)
  end
end

As far as I know, this should:

  • Run query on first call Trip.test_low_level()
  • The second time, Trip.test_low_level()it should look for a cache named "test_destinations" and return the result without querying the database .

However, no matter how many times I run the method, the request is still called. Here are the results of my terminal.

Trip.test_low_level()
  Trip Load (6.2ms)  SELECT "trips".* FROM "trips" INNER JOIN "destination_orders" ON "destination_orders"."trip_id" = "trips"."id" INNER JOIN "destinations" ON "destinations"."id" = "destination_orders"."destination_id" WHERE (destinations.id = 382)
 => #<ActiveRecord::Relation [#<Trip id: 2783, title: "Test Saving"....


Trip.test_low_levle()
  Trip Load (3.6ms)  SELECT "trips".* FROM "trips" INNER JOIN "destination_orders" ON "destination_orders"."trip_id" = "trips"."id" INNER JOIN "destinations" ON "destinations"."id" = "destination_orders"."destination_id" WHERE (destinations.id = 382)
 => #<ActiveRecord::Relation [#<Trip id: 2783, title: "Test Saving"

Even if I call the cache directly, I get the same result:

Rails.cache.fetch('test_destinations')
  Trip Load (5.0ms)  SELECT "trips".* FROM "trips" INNER JOIN "destination_orders" ON "destination_orders"."trip_id" = "trips"."id" INNER JOIN "destinations" ON "destinations"."id" = "destination_orders"."destination_id" WHERE (destinations.id = 382)
 => #<ActiveRecord::Relation [#<Trip id: 2783, title: "Test Saving"...

How can I prevent it from getting into the database a second time?

EDIT: Here are my settings in development.rb

# In the development environment your application code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = true

production.rb

# Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
+4

Source: https://habr.com/ru/post/1629764/


All Articles