【问题标题】:Ruby on Rails: How to set up "find" options in order to not use cacheRuby on Rails:如何设置“查找”选项以不使用缓存
【发布时间】:2011-06-05 21:39:57
【问题描述】:

在 Ruby on Rails 中,您可以使用以下语法从数据库中查找记录:

<model_name>.find_by_<field_name>()

示例:User.find_by_email('test@test.test')User.find_by_id(1)、...

前段时间,如果我没记错的话,我在某处读到您可以为“查找”操作显式禁用缓存,但我不记得如何操作了。

谁能帮我记住?

【问题讨论】:

  • 我没有看到默认的缓存设置...你确定吗?你检查过你的日志吗?
  • 我同意apneadiving。我不认为它是默认缓存的。

标签: ruby-on-rails caching search find ruby-on-rails-3


【解决方案1】:

你可以像这样使用ActiveRecord::QueryCache.uncached

User.find_by_email('test@test.test')
User.find_by_email('test@test.test') # Will return cached result

User.uncached do
  User.find_by_email('test@test.test')
  User.find_by_email('test@test.test') # Will query the database again
end

在控制器中,它看起来像这样:

def show # users#index action
  User.uncached do
    @user = User.find_by_email('test@test.test')
    @another_user = User.find_by_email('test@test.test') # Will query database        
  end

  User.find_by_email('test@test.test') # Will *not* query database, as we're outside of the Users.uncached block
end          

显然,在模型中,您只需要这样做:

class User < ActiveRecord::Base
  def self.do_something
    uncached do
      self.find_by_email('test@test.test')
      self.find_by_email('test@test.test') # Will query database
    end
  end
end

User.do_something # Will run both queries

【讨论】:

  • 我不明白如何使用这些代码:我必须放什么而不是'self.find(...)'?你能举个实际的例子吗?
  • 我已经更新了我的示例,但是当您只是给我抽象代码时,这很困难。你想在控制器或模型中使用它吗?如果是控制器,您可以使用我的第一个示例。如果是模型,你可以使用我的最后一个。如果您发布您正在尝试做的事情可能会更容易,而不是我试图提出对您有意义的示例。
【解决方案2】:

(注意:假设 Rails3,因为 Rails2 没有默认缓存。)

这应该可以按照您的意愿开箱即用:

  1. 查询缓存在每次操作后被销毁(http://guides.rubyonrails.org/caching_with_rails.html 第 1.5 段)
  2. 此外,似乎 (http://ryandaigle.com/articles/2007/2/7/what-s-new-in-edge-rails-activerecord-explicit-caching) 缓存也在属性上被破坏/记录更新

您是否有默认配置未涵盖的特定用例?

【讨论】:

猜你喜欢
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 2011-08-28
  • 1970-01-01
  • 2012-09-24
  • 2018-05-28
相关资源
最近更新 更多