【发布时间】:2011-12-08 20:22:23
【问题描述】:
我有一个嵌入“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) 一天四次,而标签/s 必须是持久的,与以前相同的嵌入式监视列表相关联 (. ..我不确定这是否可能,因为之前的 drop/creation )。
UPDATE 的更新(坦克到durran 支持) 不,这是不可能的:如果您清除嵌入的文档,ID 也会消失,并且每次创建新文档时都会生成新的文档。
您对如何克服这一点有任何想法吗? 在referenced relations(三个不同的集合)中拆分所有三个模型会更好吗?
【问题讨论】:
-
[RE: UPDATE of UPDATE] 但是您可以通过在创建文档时专门分配一些 id 来使 id 与以前的相同。
ids = model.embedded_docs.map(&:_id); model.embedded_docs.clear;ids.each{ |id| model.embedded_docs.create(:id => id) }。运行此代码嵌入文档将在清除前后具有相同的 id。 -
是的,非常有趣的把戏。谢谢。
标签: ruby-on-rails mongodb mongoid