我有三个模型类用户、产品和购买。采购描述了订购产品的数量。所以一个购买有一个产品,一个产品可能属于多个购买。但是关于问题的 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
如何恰当地描述关系?