1

我有三个模型类用户、产品和购买。采购描述了订购产品的数量。所以一个购买有一个产品,一个产品可能属于多个购买。但是关于问题的 Mongoid 消息:

Mongoid::Errors::InverseNotFound (
Problem:
  When adding a(n) Product to Purchase#product, Mongoid could not determine the inverse foreign key to set. The attempted key was 'purchase_id'.
Summary:
  When adding a document to a relation, Mongoid attempts to link the newly added document to the base of the relation in memory, as well as set the foreign key to link them on the database side. In this case Mongoid could not determine what the inverse foreign key was.
Resolution:
  If an inverse is not required, like a belongs_to or has_and_belongs_to_many, ensure that :inverse_of => nil is set on the relation. If the inverse is needed, most likely the inverse cannot be figured out from the names of the relations and you will need to explicitly tell Mongoid on the relation what the inverse is.

 Example:
   class Lush
     include Mongoid::Document
     has_one :whiskey, class_name: "Drink", inverse_of: :alcoholic
   end

   class Drink
     include Mongoid::Document
     belongs_to :alcoholic, class_name: "Lush", inverse_of: :whiskey
   end):

但是 mongoid 的例子并没有涵盖我的情况,因为我有“属于许多”的关系。

这是我的模型:

class Purchase
  include Mongoid::Document

  field :quantity, text: String
  has_one :product
  belongs_to :user
end

class Product
  include Mongoid::Document
  belongs_to :purchases
end

class User
  include Mongoid::Document

  has_many :purchases
end

如何恰当地描述关系?

4

2 回答 2

1

@Ajcodez 是对的,您的关系倒退了。但是,如果您实际上是在寻找 belongs_to_many 关系(一个仅在关系的一侧存储 id 的 HABTM),可以通过以下方式实现:

has_and_belongs_to_many :name, inverse_of: nil

见:https ://github.com/mongoid/mongoid/issues/2473

于 2013-10-09T22:27:31.823 回答
0

我认为你的关系倒退了。您需要每个Purchase文档都包含一个产品的 ID,这意味着Purchase属于一个产品。因此Product有很多购买。

请记住,每次写入belongs_to时,父级的 ID 都会进入文档。你真的不能belong_to <plural>

于 2013-03-21T13:43:23.033 回答