Is there a way in MongoMapper to achieve similar behavior as AR's includes method?

孤街浪徒 提交于 2019-12-12 04:49:53

问题


Is there a feature equivalent in MongoMapper to this:

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

When running Model.with_x, this avoids N queries to X. Is there a similar feature in MongoMapper?


回答1:


When it's a belongs_to relationship, you can turn on the identity map and run two queries, once for your main documents and then one for all the associated documents. That's the best you can do since Mongo doesn't support joins.

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 has a syntax for eager loading, but it works basically the same way.)



来源:https://stackoverflow.com/questions/9894784/is-there-a-way-in-mongomapper-to-achieve-similar-behavior-as-ars-includes-metho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!