0
我想我的建模與Mongoid的MongoDB數據庫,並試圖建立以下關係關係引用NN:參考1-N和Mongoid
- 用戶可以根據自己的項目
- 項目是由用戶擁有的
- 用戶可以是在項目中的合作者(但不是所有者)
- 項目有許多合作者(用戶)
小號基本上,用戶可以擁有項目並在項目上進行協作。這是兩個不同的角色。所有者,用戶,通過1-N關係,可以在項目上執行任務。合作者,用戶,通過N-N關係,可以在項目上執行一組單獨的任務。
我想出瞭解決的辦法是這樣的:
# app/models/user.rb
class User
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :email, type: String
field :username, type: String
has_many :projects
end
# app/models/project.rb
class Project
include Mongoid::Document
include Mongoid::Timestamps
field :title, type: String
field :summary, type: String
field :permalink, type: String
field :collaborator_ids, type: Array, default: []
belongs_to :user
def collaborators
arr = []
self.collaborator_ids.each do |id|
arr << User.find(id)
end
arr
end
end
這顯然並不理想:有另一種方式做到這一點?我寧願使用Mongoid的has_and_belongs_to_many
關係,而不是我擁有的數組hack中的ObjectID。
那麼,當你嘗試HABTM的合作者時發生了什麼?順便說一句,你的'協作者'方法可能只是'User.find(collaborator_ids)',不需要所有單個的'find'調用或手動數組爭奪。 –
爲什麼不爲每個項目創建':owner_id'字段,並且'User'和'Project'模型之間有'has_and_belongs_to_many'關係。然後可以創建一些簡單的函數來確定項目的所有者是誰,合作者是誰等 – alalani
@muistooshort他們之間存在衝突,因爲他們都是'User'。很酷,不知道我能做到這一點。 –