Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid: belongs_to user and has_one user

I'm using Mongoid for my app and I have a problem setting up correct relationships for Users and subscriptions.

All I need to do is to make a simple "has one and belongs to one" relationship for 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 to have a list of subscriptions 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 help.

like image 522
Martynas Jocius Avatar asked Feb 02 '23 05:02

Martynas Jocius


1 Answers

The problem is that you have two relations with the same name, and you need an inverse relation for your has_one :user relationship. You could 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
like image 92
theTRON Avatar answered Feb 07 '23 17:02

theTRON