Mongoid: owned by the user and has_one by the user

I use Mongoid for my application and I have a problem setting up the right relationships for users and subscription.

All I need to do is to make a simple "has one and applies to one" for the UserSubscription model.

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 

All I want to do is a list of subscribers for each user:

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

How to implement this? Thank you for your help.

+8
ruby-on-rails mongoid
source share
1 answer

The problem is that you have two relationships with the same name, and you need the opposite relationship for your has_one :user relationship. You can always try something like this:

 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 

Then you should be able to do things like:

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

All Articles