2012-06-13 100 views
1

我嘗試實現以下數據庫結構,但有問題的理解怎麼做使用mongoid:使用Mongoid數據庫設計的多對多關係?

我有一個模型文件,模型DocumentTeam和模型員工。用戶可以創建文檔並選擇要添加到DocumentTeam的員工。這是我大氣壓:

class Document 
    embeds_one :document_team 
end 

class DocumentTeam 
    has_many :employees 
    embedded_in :document 
end 

class Employee 
    belongs_to :document_teams 
end 

所以我的問題:我怎麼能告訴導軌自動插入選定的員工到嵌入式DocumentTeam創建文檔時?

此外,我希望能夠列出例如員工的所有情況介紹通過

Employee.first.documents 

這是可能的嗎?

感謝提前!

+0

如果您能提及簡報與其他文件的關係,以及您如何選擇所選員工,會更好? – rubish

+0

見編輯。粘貼錯誤的代碼! – Tronic

回答

1

在mongoid中,您不能引用嵌入式文檔。您可以從嵌入式文檔引用根文檔,但不能以其他方式引用。即在Employee中不能有belongs_to :document_teams。另外,作爲一個副作用,嵌入式文檔中的關係應該是單面的。你可以改變你的造型到下面來實現你想要的:

class Document 
    embeds_one :document_team 
end 

class DocumentTeam 
    has_and_belongs_to_many :employees, inverse_of: nil 
    embedded_in :document 
end 

class Employee 
    def documents 
    Document.where('document_team.employee_ids' => self.id) 
    end 
end 

這將讓你使用Employee.first.documents,但你不能把它作爲一個關係,繼續做的事情你可以做的關係,如重新分配,推拉文件。您必須通過DocumentTeam管理團隊和員工關係,但可以直接訪問員工文檔以供閱讀。

PS:Document id不是類的好名字,我想它可能會在某些情況下與Mongoid :: Document衝突。