2011-06-13 60 views
3

由於MongoDB中的老手,我創建了以下結構:Mongoid與「外鍵」

User: { 
    name: str, 
    email: ... 
} 

Gift: { 
    # author and receiver refer to User objects obviously 
    author: object_id(...),  
    receiver: object_id(...), 

    name: str 
    ... 
} 

而且我想在mongoid正確映射這樣的:

class User 
    include Mongoid::Document 

    has_many :gifts 
end 

class Gift 
    include Mongoid::Document 

    belongs_to :user 
end 

然而,映射不正確。 g = Gift.first; g.author沒有定義。我如何做參考?

從技術上講,它是:

User <--- 1: N via author---> Gift <--- N:1 via receiver---> User 

(這就意味着用戶可以是許多禮物的作者,並且用戶可以是許多禮物接收者,而是一個禮物只能有1個作家和接收器)。

Plz help !!!

回答

5

你可能要使用Rails更好的運氣,如果禮物是這樣的:

Gift: { 
    # author and receiver refer to User objects obviously 
    author_id: object_id(...),  
    receiver_id: object_id(...), 

    name: str 
    ... 
} 

,然後添加一個:foreign_key禮物:

class Gift 
    include Mongoid::Document 

    belongs_to :user, :foreign_key => 'author_id' 
end 
+0

是啊,我不知道:foreign_key將在沒有活動記錄的情況下工作(我意識到它們也在mongoid中定義) – disappearedng 2011-06-13 08:09:06