【问题标题】:Mongoid: Caching Eager Loaded DocumentsMongoid:缓存渴望加载的文档
【发布时间】:2014-05-13 16:00:29
【问题描述】:

我们有这个代码:

class Band
  include Mongoid::Document
  has_many :albums
end

class Album
  include Mongoid::Document
  belongs_to :band
end

@bands = Band.includes(:albums).entries

这太棒了,因为现在我可以运行@bands.first.albums 而无需访问数据库。 但是现在,如果我们将这个包含写入到 Rails 缓存中......

Rails.cache.write('bands', @bands) 

...然后我们读取缓存。

bands = Rails.cache.read('bands')

这将返回一个乐队文档数组...

[#<Band _id: 536a53c969702d208f240000, created_at: 2014-05-07 15:39:53 UTC, updated_at: 2014-05-08 15:55:29 UTC, name: "Pink Floyd", fan_count: 394857, #<Band _id: 536adf2a69702d1574130000, created_at: 2014-05-08 01:34:34 UTC, updated_at: 2014-05-08 01:35:40 UTC, name: "Tool", fan_count: 2958394, #<Band _id: 536bcad169702d743e1e0000, created_at: 2014-05-08 18:20:01 UTC, updated_at: 2014-05-08 18:27:10 UTC, name: "My Morning Jacket", fan_count: 3945734]

...然后我们就拿不到专辑了。

bands.first.albums

NoMethodError: undefined method 'albums' for #<Array:0x00000104df50c0>

有没有一种特殊的方法可以用 Rails 或 Mongoid 缓存这些预先加载的文档?

仅供参考,我们使用的是 Mongoid 4。

【问题讨论】:

  • Rails.cache.read('bands') 的内容是什么?那是一个数组吗?你能检查那个元素并发布结果吗?
  • @ArthurNeves:我编辑了这个问题。感谢您的评论。
  • 那太奇怪了。当你做bands.first时,它返回相同的数组?
  • @ArthurNeves:不,当我运行bands.first 时,它会返回第一个乐队。但我不能运行bands.first.albums。

标签: ruby-on-rails caching mongoid


【解决方案1】:

这似乎是 Mongoid 上的一个急切加载问题。您能否转到 https://github.com/mongoid/mongoid/issues/new 并打开一个新问题,以便我们在发布最终 4.0.0 版本之前对其进行修复。

谢谢

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 2011-01-25
    相关资源
    最近更新 更多