0

假设我有一个名为 Foo 的 mongoid 模型,它嵌入了许多 Bar。

class Foo
    ...
    embeds_many :bar
    ...
end

class Bar
    ...
    embedded_in :foo
    ...
end

我想创建一个 Bar 链接到它自己的关系。该关系将始终涉及嵌入在同一个 Foo 文档中的两个文档。在调用关系时,我似乎无法做到这一点而没有返回 nil。我试过了

belongs_to :discovered_by, :class_name => 'Bar'

并且

has_one :discovered_by, :class_name => 'Bar'

虽然在 Bar 文档中设置了 found_by id,并在我尝试执行以下操作时指向另一个 Bar 文档,但我得到 nil(假设第一个 Foo 的第一个 Bar 设置了 found_by_id)

Foo.first.bars.first.discovered_by

尽管文档设置了 id,这将始终返回 nil。知道为什么会这样吗?谢谢你的帮助。

4

1 回答 1

1

You cannot have references to embedded models - even when they're both embedded in the same document. If you correctly configure the relationship

belongs_to :discovered_by, :class_name => 'Bar', inverse_of: :discovered
has_one :discovered, :class_name => 'Bar', inverse_of: :discovered_by

Mongoid will raise a Mongoid::Errors::MixedRelations exception. Maybe you could reconsider if embedding these objects is still the best choice. A workaround is storing only the id and query the parent object:

class Bar
    include Mongoid::Document
    embedded_in :foo
    field :discovered_by_id, type: Moped::BSON::ObjectId

    def discovered_by
      foo.bars.find(discovered_by_id) if discovered_by_id
    end

    def discovered_by=(bar)
      self.discovered_by_id = bar.id
    end
end
于 2013-03-29T16:49:04.957 回答