Mongoid:缓存预加载文档

4
我们有这段代码:
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而不用查询数据库。 但是,如果我们将这个 includes 写入 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') 的内容是什么?那是一个数组的数组吗?你能检查一下这个元素并发布结果吗? - Arthur Neves
@ArthurNeves:我编辑了这个问题。感谢您的评论。 - Charlie
这很奇怪。当你执行 bands.first 时,它返回相同的数组? - Arthur Neves
@ArthurNeves:不,当我运行bands.first时,它可以正常返回第一个乐队。但是我无法运行bands.first.albums。 - Charlie
1个回答

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接