2013-09-26 49 views
0

我是mongoid的新手,並且偶然發現了一個問題。我有一個用戶模型和一個組模型,我希望用戶能夠創建組和另一個用戶來加入該組。與我從AR的經驗,我會解決這個通過has_many:通過,但與mongoid我沒有這個選項。Mongoid和用戶組

我一直在嘗試這個解決方案How to implement has_many :through relationships with Mongoid and mongodb?但我無法獲得@ group.users。

我將不勝感激所有可能的幫助。 :)

+1

http://mongoid.org/en/mongoid/docs/relations.html#has_and_belongs_to_many – apneadiving

+0

^應該是這樣的答案 –

+0

謝謝!那是我第一次衝動。對於用戶加入某個組的好處是什麼?我必須承認,我從未使用過HABTM。 – Petter

回答

0

這應該做你所需要的。

class User 
    include Mongoid::Document 
    field :name 
    has_and_belongs_to_many :groups 
end 

class Group 
    include Mongoid::Document 
    has_and_belongs_to_many :users 
end 

u = User.create!(name: "arthurnn") 
g = Group.create!(users: [u])