2

我有以下型号:

class Foo
 has_and_belongs_to_many :bars
end

class Bar
 has_and_belongs_to_many :foos
end

每个代表Foo实例的文档都有一个名为 的数组字段bar_ids。每当从数据库中检索到 Foo 对象时,Mongoid 也会检索该对象的内容bar_ids。当文档有 1000 个 id 时,这可能会导致性能问题,即

> Foo.first
#<Foo _id: 4fed60aa2bdf061c2c000001, bar_ids: [1, 2, 3.... 5000]>

在大多数情况下,我不需要加载bar_ids. 有没有办法可以指示模型延迟加载bar_ids

4

1 回答 1

2

我在群里问了同样的问题,mongoid得到了答案。本质上,需要阅读三个 gem 的文档才能理解mongoid 3(mongoid、moped 和 origin)。

这是gem的相关文档部分。or子句可用于过滤生成的文档结构originwithoutonly

选择性加载:

Foo.without(:bar_ids).first

有选择地重新加载:

def reload_fields(*fields)
  return self if fields.empty? or new_record?
  # unscope and prevent loading from indentity map
  fresh = Mongoid.unit_of_work(disable: :current) do
    self.class.unscoped.only(*fields).find(id)
  end
  fields.each do |attr| 
    write_attribute(attr, fresh.read_attribute(attr))
    remove_change(attr) # unset the dirty flag for the reloaded field
  end
  self
end
于 2012-06-29T20:23:48.200 回答