2011-07-07 46 views
2

我有以下型號Mongoid 1..1多態引用關係

class Track 
    include Mongoid::Document 
    field :artist, type: String 
    field :title, type: String 
    has_many :subtitles, as: :subtitleset 
end 

class Subtitle 
    include Mongoid::Document 
    field :lines, type: Array 
    belongs_to :subtitleset, polymorphic: true 
end 

class User 
    include Mongoid::Document 
    field :name, type: String 
    has_many :subtitles, as: :subtitleset 
end 

在我的Ruby代碼,當我創建一個新的字幕我推着它在適當的跟蹤和用戶是這樣的:

Track.find(track_id).subtitles.push(subtitle) 
User.find(user_id).subtitles.push(subtitle) 

問題是,它只能在用戶中推送,而不在跟蹤中。但是如果我刪除第二行,它會將它推到軌道上。那麼爲什麼不爲兩者工作呢?

我得到這個字幕文件:

"subtitleset_id" : ObjectId("4e161ba589322812da000002"), 
"subtitleset_type" : "User" 

回答

2

如果字幕屬於東西,它指向的東西的ID。一個字幕不能同時屬於兩個事物。如果所有物是多形的,則字幕可以屬於未指定類別的東西 - 但它仍然不能同時屬於兩個東西。

你想:

class Track 
    include Mongoid::Document 
    field :artist, type: String 
    field :title, type: String 
    has_many :subtitles 
end 

class Subtitle 
    include Mongoid::Document 
    field :lines, type: Array 
    belongs_to :track 
    belongs_to :user 
end 

class User 
    include Mongoid::Document 
    field :name, type: String 
    has_many :subtitles 
end 

,然後你將能夠:

Track.find(track_id).subtitles.push(subtitle) 
User.find(user_id).subtitles.push(subtitle) 
+1

我在下面這裏指定的多態行爲:http://mongoid.org/docs/relations/referenced /1-n.html(向下滾動到頁面底部)。我也會嘗試你的建議。 –