views:

47

answers:

1

I'm looking to Eager Load Associated Documents using MongoMapper. Say I have an author with a :has_one condition to a Post, I should be able to load the author using a single query

Post.find(:all, :include => :author)

Any suggestions?

+1  A: 

UPDATE: The code below is just as models workflow.. I tried it after some coding and it didnt work!

Lets say you have Post model and User model.

User has_many posts, and you want All the users (authors) with their posts.

Here a tip to handle it. and my example is fetching one post.

post.rb

class Post
  include MongoMapper::Document

  key :title, String
  key :body, String
  key :user_id, ObjectId

  belongs_to :user

end

and user.rb

class User
  include MongoMapper::Document
  key :name
  many :posts, :embed => :title
end

Now,

u = User.first
p = u.posts.first

puts p.title # read it from embedded doc
puts p.body # lazy loading

The trick here is to embed the mostly common fields like the name of the user, _id, user slug, etc.

I didnt test what above, but you have to give a try!

Best --Amr

amrnt
Wish there was a simpler way but will take what I can get
Greg
I tried it for real! (after fixing and adding some codes) But unfortunately it didnt work. I think theres a chance in Mongoid, see this pull request: http://github.com/mongoid/mongoid/pull/391
amrnt