Mongoid:belongs_to user和has_one user

时间:2012-05-02 08:31:52

标签: ruby-on-rails mongoid

我正在为我的应用程序使用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

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

1 个答案:

答案 0 :(得分:11)

问题在于您有两个具有相同名称的关系,并且您需要与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