so i’m using Mongoid and i want to return an object with it’s refference. lets say i have:
class User
include Mongoid::Document
has_many :pictures
end
class Picture
include Mongoid::Document
belongs_to :user
end
the problem is with this code:
users = User.all #goes to the db
users.each do |user|
pic = user.pictures.first # <--- bad! hitting the db again here
end
so, how can return an object (user) that contains it’s refference so i wont need to hit the db again?
This would normally be done with joining in ActiveRecord. Something like this:
But since MongoDB doesn’t support joins, there’s no way to load parent document and its referenced documents in one go. If this becomes a problem, you should consider embedding pictures in a user document (this, however, may cause more serious performance penalties).
Update
Mongoid has a way to eagerly load (search the page for “Eager Loading”) referenced relations, but still separate queries are made. Database won’t be hit on subsequent access of a relation.