开发者

Mongoid 1..N polymorphic referenced relations

I have the following models

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

class Subtitle
  include Mongoid::Document
  fiel开发者_StackOverflowd :lines, type: Array
  belongs_to :subtitleset, polymorphic: true
end

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

And in my ruby code when I create a new Subtitle I'm pushing it in the appropriate Track and User like this:

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

The problem is that it gets pushed only in the User and not in the Track also. But if I remove the second line it gets pushed it the Track. So why isn't working for both?

I get this in the Subtitle document:

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


If a subtitle belongs to something, it has an ID pointing to that something. A subtitle cannot belong to two somethings at once. If the belonging is polymorphic, a subtitle can belong to something whose class is not specified - but it still cannot belong to two somethings at once.

You want:

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

And then you will be able to:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜