【问题标题】:Rails cache with where clause带有 where 子句的 Rails 缓存
【发布时间】:2013-07-05 17:34:17
【问题描述】:

型号

class Line < ActiveRecord::Base
   attr_accessible :num, :foreign_id

   def self.cached_foreign(q)
       Rails.cache.fetch([name,"foreign"+q.to_s]) { where(:foreign_id => q) }
   end

end

对于上述模型,当Line.cached_foreign(1)重复运行时,它总是执行sql语句。

这里有什么问题?理想情况下,它应该从缓存中返回重复调用。

这在使用 find 时似乎可以正常工作,但在使用 where 时却不行。

【问题讨论】:

  • 它是否也在使用find_by_foreign_id 检索新记录?
  • @Vishal 使用 find 时效果很好。

标签: ruby-on-rails caching


【解决方案1】:

它适用于:

where(foreign_id: q).all

这是因为没有.all 的语句被懒惰地评估,所以在你的缓存中你存储代理对象,当它真正需要时被评估。如果添加.all,则将实际记录集存储在缓存中。

【讨论】:

  • @Nishant 您确定在尝试之前清除了缓存吗?
  • 与@Nishant 相同的问题。使用“全部”没有帮助
  • @codeObserver 它不像我在 Rails 4 中描述的那样工作。
  • 嗨 Marek,感谢您的回答。知道如何解决这个问题吗?我尝试搜索,但想不出一个好的方法。我的用例是 1] a = User.where(something) 2] ids = User.where(something).pluck(:id) 3] c = a.where.not(ids) 。我想缓存 a 和 c ,但只是缓存 'a' 可以提高性能。再次感谢!
  • @codeObserver 你为什么不问一个问题?您可以在 cmets 中链接到您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-23
  • 2011-08-02
相关资源
最近更新 更多