Mongoid :: Errors :: MixedRelations [英] Mongoid::Errors::MixedRelations
问题描述
我有一个嵌入"一对多的用户模型"监视列表如下:
I've a User model embedding "one to many" Watchlists like the following :
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
关注列表还应该引用许多标签模型,反之亦然:
The Watchlist should also references a many to many Tag model and vice versa :
class Tag
include Mongoid::Document
field :name, type: String
has_and_belongs_to_many :watchlists
end
无论如何,这会导致错误,并且似乎不可能实现这种混合"关系:
Anyway, that's causing an error and seems that kind of "mixed" relation is not possible :
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),而标签必须是持久性的,并且与以前的嵌入的监视列表相关. ..由于先前的drop/creation,我仍然不确定是否可以实现.
UPDATE Please note that watchlist, has to be dropped (user.watchlists.clear) than re-created (user.watchlists.find_or_create_by) four times a day, while Tag/s have to be persistent, relating the same embedded watchlists as before ( ... I'm not sure that is possible anyway, because of previous drop/creation ).
UPDATE的更新(用于 durran的坦克支持) 不,这是不可能的:如果您清除嵌入式文档,则ID也将消失,并且每次创建新ID时都会生成新ID.
UPDATE of UPDATE ( tanks to durran support ) No, that's not possible: If you clear the embedded docs, the ids are gone as well, and new ones will get generate each time you create a new one.
您对如何克服它有任何想法吗? 在引用关系(三个不同的集合)中拆分所有三个模型是否更好?
Do you have any idea on how to overcome that ? Is it better to split all three models in referenced relations ( three different collections )?
推荐答案
在mongoid中,您不能引用嵌入式文档.所以问题出在您的标签模型中定义habtm.您可以在嵌入式监视列表中具有HABTM,而没有任何反比关系.
In mongoid you can't have references to embedded documents. So the problem is in your tag model defining habtm there. You can have HABTM in embedded watchlists, without any inverse relation.
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
但是,如果必须在标记中引用监视列表,则可以像Tyler所指出的那样,在两侧手动维护ID数组.
But if you must have references to watchlists in tags, you can manually maintain array of ids on both sides as already pointed out by Tyler.
这篇关于Mongoid :: Errors :: MixedRelations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!