怎么形容属于很多?

时间:2013-03-21 13:11:09

标签: ruby mongoid

我有三个模型类User,Product和Purchase。购买描述了订购产品的数量。因此,购买有一种产品,而产品可能属于许多购买。但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

如何正确描述关系?

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

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

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