我有三個模型類用戶,產品和購買。採購描述訂購產品的數量。所以購買有一種產品,並且產品可能屬於許多購買。但關於問題的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
如何正確形容關係?
我建議不過,如果你實際上是在尋找一個belongs_to_many關係(HABTM只存儲在關係的一個側面IDS),可以通過實施寫作產品'has_many'購買和購買'belongs_to'產品。否則,最終每個產品都會購買一次。另外,請注意購買下的錯字:'belongs_to:user' – depa 2013-03-21 13:22:16
@mdepolli感謝您提供關於錯字的提示。當然,它會起作用。但我認爲這個解決方案沒有足夠清楚地描述關係語義。 – 2013-03-21 13:34:58