我試圖跟蹤用戶的當前,先前和選擇(期末更改)訂閱狀態。Mongoid嵌入一個類作爲多個字段
在月結束時,如果chosen_subscription != current_subscription
,current_subscription
被更改。
class User
include Mongoid::Document
embeds_one :previous_subscription, class_name: "Subscription"
embeds_one :current_subscription, class_name: "Subscription"
embeds_one :chosen_subscription, class_name: "Subscription"
end
class Subscription
include Mongoid::Document
embedded_in :user
field :plan, type: String
field :credits, type: Integer
field :price_per_credit, type: BigDecimal
field :start, type: Date
field :end, type: Date
end
Mongoid要我來指定這個更多的方式,沒有任何意義對我說:
Mongoid::Errors::AmbiguousRelationship:
Problem:
Ambiguous relations :previous_subscription, :current_subscription, :chosen_subscription defined on User.
Summary:
When Mongoid attempts to set an inverse document of a relation in memory, it needs to know which relation it belongs to. When setting :user, Mongoid looked on the class Subscription for a matching relation, but multiples were found that could potentially match: :previous_subscription, :current_subscription, :chosen_subscription.
Resolution:
On the :user relation on Subscription you must add an :inverse_of option to specify the exact relationship on User that is the opposite of :user.
這發生在我覆蓋現有current_subscription。我想,在這個時候,Mongoid想要取消註冊舊訂閱用戶的訂閱。
當然,每個認購對象只屬於一個用戶和user == user.previous_subscription.user == user.current_subscription.user == user.chosen_subscription.user
然而,它並不意義,我要告訴Subscription
即user
是三個中的任何一個的倒數。
我應該如何構建它?
我不太清楚你將如何構建它沒錯,但你可以試試看單身谷歌組。 mongoid告訴你的問題是如果你執行'subscription.user = some_user',它不知道你是從用戶的角度來談論你正在談論的。如果你不打算在你的代碼中使用'subscription.user =',你也可以嘗試設置'inverse_of:nil'。 – rubish
我從來沒有直接設置subscription.user。我認爲當我設置用戶。* _訂閱時,它會隱式設置。 inverse_of:nil對我來說工作得很好。如果你想爲它創建一個答案,我會標記它是正確的。 – Jan
我已將評論擴展到答案中,並提供了一些更多信息和一些建議。我不相信這是理想的解決方案,但在大多數情況下適用於我。 – rubish