问题
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