9

我正在为我的应用程序使用 Mongoid,但在为用户和订阅设置正确关系时遇到问题。

我需要做的就是为 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

如何实施?谢谢你的帮助。

4

1 回答 1

12

问题是你有两个同名的关系,你的关系需要一个逆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
于 2012-05-02T14:18:49.223 回答