开发者

Eager Loading of Associations using MongoMapper

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, :inc开发者_Go百科lude => :author)

Any suggestions?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜