Rails.cache.fetch异常:TypeError(<modelname>不能引用)</modelname>

时间:2011-10-05 16:41:12

标签: ruby-on-rails caching

我正在使用漂亮的Rails.cache.fetch实现一些缓存。但是,在某个特定情况下,有时我会遇到异常:

TypeError in EmloController#index

Emlo can't be referred to

app/controllers/emlo_controller.rb:320:in `get_employees'
app/controllers/emlo_controller.rb:356:in `prepare_json_response'
app/controllers/emlo_controller.rb:23:in `block (2 levels) in index'
app/controllers/emlo_controller.rb:15:in `index'

在第一次尝试时,fetch似乎总是会爆炸(使用上面的内容),然后只要fetch在到期时就可以正常工作。我知道我错过了什么,所以一双新鲜的眼睛会很好。

这是调用缓存提取的方法:

def get_employees

  # This is for a AJAX refresh loop, so a 5-second cache actually helps quite a bit
  Rails.cache.fetch('emlo_all', :expires_in => 5.seconds, :race_condition_ttl => 1) do

    conditions = (params[:id]) ? {:user_id => params[:id]} : nil

    selections = [
      'employee_locations.id AS emlo_id',
      'employee_locations.status_id',
      'employee_locations.notes',
      'employee_locations.until',
      'employee_locations.updated_at',
      'employee_locations.user_id',
      'location_states.id AS state_id',
      'location_states.title AS status_string',
      'location_states.font_color',
      'location_states.bg_color',
      'users.displayname',
      'users.email',
      'users.mobile',
      'users.department',
      'users.extension',
      'users.guid',
      'users.dn'
    ].join(', ')

    Emlo.all(
        :select => selections,
        :joins => 'LEFT JOIN users ON employee_locations.user_id=users.id LEFT JOIN location_states ON employee_locations.status_id=location_states.id',
        :conditions => conditions,
        :order => 'users.displayname ASC'
    )
  end
end

2 个答案:

答案 0 :(得分:15)

config.action_controller.perform_caching = trueconfig.cache_classes = false时,在开发模式中出现此问题 - 似乎ActiveRecord对象无法与Rails.cache一起存储。

但是,如果您需要在开发模式中启用config.action_controller.perform_caching来测试缓存,那么您还必须启用config.cache_classes。但这是暂时的,因为在更改资产管道中的类或文件后,您必须重新启动开发服务器。

禁用缓存后,我会使用Rails.cache.write(some_name, some_value) if Rails.env.production?来防止缓存在开发中爆炸。 Rails.cache.read()似乎没有受到影响。

答案 1 :(得分:-1)

根据应用程序的结构,您可能会遇到如下错误: TypeError(无法引用用户) 这个错误是由一些缓存重新加载的疯狂引起的:一些gem植入的中间件被缓存。但在开发过程中,你的课程通常不是。因此,某些类别在某些情况下可能无法使用,例如如果您在过滤器之前使用某些引擎提供的用户身份验证。您应该能够通过启用类缓存来摆脱上述错误。尝试一下(然后重启服务器):

development.rb

config.cache_classes = true

如果错误消失了,你很幸运。但是由于在开发中缓存类是不可行的,所以再次关闭类缓存并明确要求无法引用的类。即:

开发顶部.rb

要求'app / models / user'