我正在尝试理解关闭identity_map时的急切加载(includes
)行为。
class Account
has_and_belongs_to_many :subscriptions
end
a = Account.includes(:subscriptions).first # makes first two calls to the database
a.subscriptions # returns nothing
a.subscriptions.map(&:name) # makes the 3rd call to the database.
根据文档includes
选择器应该仅在启用identity_map时才起作用。
但在我的情况下,即使禁用了identity_map,Mongoid库也会尝试加载包含的关联。当稍后访问关联时,这会导致对数据库的冗余调用。
MOPED: yyyy:10019 QUERY database=xxxx collection=accounts
selector={"$query"=>{}, "$orderby"=>{:_id=>1}}
flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (148.0079ms)
MOPED: yyyy:10019 QUERY database=xxxx collection=subscriptions
selector={"_id"=>{"$in"=>["50eaad6b6f758a601a000017", "50eaad7e6f758a601a000036"]}}
flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil (573.0329ms)
MOPED: yyyy:10019 QUERY database=xxxx collection=subscriptions
selector={"$and"=>[{"_id"=>{"$in"=>["50eaad6b6f758a601a000017",
"50eaad7e6f758a601a000036"]}}]}
flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil (586.0329ms)