Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top