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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With