在MongoMapper中是否有一种方法可以实现与AR包含方法类似的行为?

时间:2012-03-27 17:44:22

标签: ruby mongomapper eager-loading

MongoMapper中是否有与此类似的功能:

class Model < ActiveRecord::Base
  belongs_to :x
  scope :with_x, includes(:x)
end

运行Model.with_x时,这可以避免对X进行N次查询。 MongoMapper中是否有类似的功能?

1 个答案:

答案 0 :(得分:1)

当它是belongs_to关系时,您可以打开identity map并运行两个查询,一次针对您的主要文档,然后针对所有相关文档。这是你可以做的最好的,因为Mongo不支持连接。

class Comment
  include MongoMapper::Document
  belongs_to :user
end

class User
  include MongoMapper::Document
  plugin MongoMapper::Plugins::IdentityMap
end

@comments = my_post.comments                # query 1
users = User.find(@comments.map(&:user_id)) # query 2

@comments.each do |comment|
  comment.user.name # user pulled from identity map, no query fired
end

(Mongoid有一个syntax for eager loading,但它的工作方式基本相同。)