Mongoid ::错误:: MixedRelations

BBJ*_*BJ3 3 ruby-on-rails mongodb mongoid

我有一个用户模型嵌入" 一对多 "的关注列表,如下所示:

class User 
  include Mongoid::Document

  field :uid
  field :name     
  field :user_hash

  embeds_many :watchlists
end


class Watchlist
  include Mongoid::Document

  field :html_url
  field :description

  #field :name
  field :fork_, :type => Boolean

  field :forks, :type => Integer
  field :watchers, :type => Integer

  field :created_at, :type => DateTime
  field :pushed_at, :type => DateTime

  field :avatar_url

  embedded_in :user
  has_and_belongs_to_many :tags
end
Run Code Online (Sandbox Code Playgroud)

监视列表还应引用多对多 Tag模型,反之亦然:

class Tag
  include Mongoid::Document
  field :name, type: String

  has_and_belongs_to_many :watchlists
end
Run Code Online (Sandbox Code Playgroud)

无论如何,这导致了一个错误,似乎不可能出现这种"混合"关系:

Mongoid::Errors::MixedRelations (Referencing a(n) Watchlist document from the Tag document via a relational association is not allowed since the Watchlist is embedded.):
 app/controllers/home_controller.rb:53:in `tagging'
Run Code Online (Sandbox Code Playgroud)

更新 请注意,必须删除监视列表(user.watchlists.clear),而不是每天重新创建(user.watchlists.find_or_create_by)四次,而Tag/s必须是持久的,与之前的嵌入式监视列表相关联( ......无论如何,我不确定这是否可能,因为先前的下降/创造.

UPDATE的更新(坦克到durran支持)不,这是不可能的:如果你清除嵌入的文档,那么id也会消失,每次你创建一个新的时候都会生成新的.

你对如何克服这个问题有任何想法吗?将所有三个模型拆分为引用关系(三个不同的集合)是否更好?

rub*_*ish 5

在mongoid中,您不能引用嵌入式文档.所以问题在于你的标签模型中定义了habtm.您可以在嵌入式监视列表中使用HABTM,而没有任何反向关系.

class User 
  include Mongoid::Document
  embeds_many :watchlists
end

class Watchlist
  include Mongoid::Document
  embedded_in :user
  has_and_belongs_to_many :tags, inverse_of: nil
end

class Tag
  include Mongoid::Document
end
Run Code Online (Sandbox Code Playgroud)

但是,如果必须在标签中引用关注列表,则可以手动维护两侧的ID数组,如Tyler已经指出的那样.