我有一个嵌入“one to many”监视列表的用户模型,如下所示:
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
监视列表还应引用 many to many标签模型,反之亦然:
class Tag
include Mongoid::Document
field :name, type: String
has_and_belongs_to_many :watchlists
end
无论如何,这会导致错误,并且似乎不可能存在那种“混合”关系:
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'
更新 请注意,监视列表必须每天四次删除(user.watchlists.clear)而不是重新创建(user.watchlists.find_or_create_by),而 Tag/s 必须持久,与以前相同的嵌入式监视列表相关( . .. 我不确定这是否可能,因为之前的删除/创建)。
UPDATE of UPDATE(支持durran) 不,那是不可能的:如果您清除嵌入式文档,id 也会消失,并且每次您创建一个新文档时都会生成新的。
你知道如何克服这个问题吗? 在referenced relations中拆分所有三个模型是否更好? (三个不同的系列)?
最佳答案
在 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
但是如果您必须在标签中引用监视列表,您可以手动维护两侧的 id 数组,正如 Tyler 已经指出的那样。
关于ruby-on-rails - Mongoid::错误::混合关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8437181/