2013-03-21 67 views
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 

如何正確形容關係?

+0

我建議不過,如果你實際上是在尋找一個belongs_to_many關係(HABTM只存儲在關係的一個側面IDS),可以通過實施寫作產品'has_many'購買和購買'belongs_to'產品。否則,最終每個產品都會購買一次。另外,請注意購買下的錯字:'belongs_to:user' – depa 2013-03-21 13:22:16

+0

@mdepolli感謝您提供關於錯字的提示。當然,它會起作用。但我認爲這個解決方案沒有足夠清楚地描述關係語義。 – 2013-03-21 13:34:58

回答

0

我想你有關係倒退。您需要每個Purchase文檔包含產品的ID,這意味着Purchase屬於產品。因此Product有很多購買。

記得每次你寫belongs_to時,父母的身份證進入文檔。你不能真的belong_to <plural>

1

@Ajcodez是正確的,你的關係是向後的。

has_and_belongs_to_many :name, inverse_of: nil

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

+0

如果你想命名關係除了模型名稱:'has_and_belongs_to_many:friends,class_name:'User',inverse_of:nil' – colllin 2014-01-09 15:47:01

+0

現在可以在這裏找到該問題:https://jira.mongodb.org/browse/MONGOID-2473 – 2016-03-22 09:50:05