2010-09-03 69 views
2

我正在尋找使用MongoMapper的Eager Load Associated Documents。假設我的作者有一個:has_one條件的帖子,我應該可以使用單個查詢加載作者使用MongoMapper進行關聯加載

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

任何建議?

+0

關於同一主題,這將是巨大的,如果我能有* *內嵌對象這反過來有關聯的數組相同。例如:'question = Question.first; question.comments(:include =>:user)'(註釋是一個嵌入式模型)。 – hsribei 2010-10-21 21:00:45

回答

1

更新:下面的代碼就像模型工作流程..我嘗試了一些編碼後,它沒有工作!

可以說你有Post模型和用戶模型。

用戶has_many帖子,並且您希望所有用戶(作者)及其帖子。

這裏有一個提示來處理它。我的例子是獲取一個帖子。

post.rb

class Post 
    include MongoMapper::Document 

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

    belongs_to :user 

end 

和user.rb

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

現在,

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

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

這裏的竅門是嵌入大多是常見的領域,如用戶名,_id,用戶slu,等

我沒有測試以上,但你必須嘗試!

最佳 --Amr

+0

希望有一個更簡單的方法,但將採取我所能得到的 – Greg 2010-10-25 23:07:58

+0

我試過它的真實! (修復和添加一些代碼後)但不幸的是它沒有工作。我認爲在Mongoid中有這樣一個機會,看到這個請求:http://github.com/mongoid/mongoid/pull/391 – amrnt 2010-10-26 18:10:52

相關問題