Ruby on rails 在使用mongoid gem时,延迟加载has_和_属于_many字段

Ruby on rails 在使用mongoid gem时,延迟加载has_和_属于_many字段,ruby-on-rails,mongoid,Ruby On Rails,Mongoid,我有以下型号: class Foo has_and_belongs_to_many :bars end class Bar has_and_belongs_to_many :foos end 表示Foo实例的每个文档都有一个名为bar\u id的数组字段。当从数据库中检索到一个Foo对象时,Mongoid也会检索bar\u id的内容。当文档有1000个ID时,这可能会导致性能问题,即 > Foo.first #<Foo _id: 4fed60aa2bdf061c2c0000

我有以下型号:

class Foo
 has_and_belongs_to_many :bars
end

class Bar
 has_and_belongs_to_many :foos
end
表示
Foo
实例的每个文档都有一个名为
bar\u id
的数组字段。当从数据库中检索到一个Foo对象时,Mongoid也会检索
bar\u id
的内容。当文档有1000个ID时,这可能会导致性能问题,即

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

在大多数情况下,我不需要加载
条形码ID
。是否有方法可以指示模型延迟加载
条ID

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

以下是
origin
gem的相关文档。不带的
或仅
子句可用于筛选生成的文档结构

选择性加载:

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
有选择地重新加载:

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