我的用户模型嵌入了“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更新(坦克到durran支持) 不,这是不可能的:如果您清除嵌入式文档,那么ID也会消失,每次创建新文件时都会生成新的文件。
你对如何克服这个问题有任何想法吗? 在referenced relations(三个不同的集合)中拆分所有三个模型是否更好?
答案 0 :(得分: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
但是,如果您必须在标签中引用关注列表,则可以手动维护两侧的ID数组,如Tyler已经指出的那样。
答案 1 :(得分:2)
不是你正在寻找的答案,而是...为了它的价值,每当我在mongoid中使用HABTM关系时,它都是错误的或者不起作用。我不知道这是否已经修复,但如果你坚持只使用模型中的数组,并且在关系的反面,你应该是金色的。无论如何,这几乎就是代码会为你做的事情。
是的,你必须做更多的工作来维持这种关系,但它实际上就像预期的那样。
祝你好运。