2011-07-07 70 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(向下滚动到页面底部)。我也会尝试你的建议。 –