Rails 4 - 低级缓存仍在查询数据库

时间:2016-02-21 11:13:35

标签: ruby-on-rails ruby-on-rails-4 caching activerecord

我跟随low-level caching tutorial found on Heroku's website。几乎逐字复制他们的例子,这是我的方法:

Trip.test_low_level()

据我所知,这应该是:

  1. 第一次调用Trip.test_low_level()时执行查询
  2. 第二次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" ,它应该查找名为&#39; test_destinations&#39;的缓存。并返回结果而不查询数据库
  3. 但是,无论我运行该方法多少次,仍然会调用该查询。以下是我的终端的结果。

    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"...
    

    即使我直接调用缓存,也会得到相同的结果:

    # In the development environment your application's 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
    

    如何防止它第二次访问数据库?

    编辑:这是我在development.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
    

    Production.rb

    webservice

0 个答案:

没有答案