2012-05-02 29 views
8

我爲我的應用使用Mongoid,並且遇到了爲用戶和訂閱設置正確關係的問題。Mongoid:belongs_to用戶和has_one用戶

我需要做的就是爲UserSubscription模型創建一個簡單的「擁有一個屬於一個」關係。

class User 
    has_many :user_subscriptions 
end 

class UserSubscription 
    belongs_to :user 

    has_one :user # user2 to which user1 is subscribed 
    field :category, :String 
end 

所有我想要做的是爲每一個用戶的訂閱列表:

> user1.user_subscriptions # list of subscription objects 
> user1.user_subscriptions << UserSubscription.create(:user => user2, :category => 'Test') 
> user1.user_subscriptions.where(:user => user2).delete_all 

如何實現這一點?謝謝你的幫助。

回答

10

問題是你有兩個同名的關係,並且你需要一個與你的has_one :user關係相反的關係。你總是可以嘗試這樣的事情:

class User 
    include Mongoid::Document 

    has_many :subscriptions 
    has_many :subscribers, :class_name => "Subscription", :inverse_of => :subscriber 
end 

class Subscription 
    include Mongoid::Document 

    field :category 

    belongs_to :owner, :class_name => "User", :inverse_of => :subscriptions 
    belongs_to :subscriber, :class_name => "User", :inverse_of => :subscribers 
end 

那麼你應該能夠做這樣的事情:

> user1.create_subscription(:subscriber => user2, :category => "Test") 
> user1.subscriptions.where(:subscriber => user2).delete_all 
+1

謝謝!當我將用戶類的has_many關係更改爲: has_many:subscriptions,:class_name =>「Subscription」,:inverse_of =>:owner –