0

I have a Users model and want users to be able to Subscribe to another User to get notifications when they post things.

This is sort of a has_many self join and a many_to_many self join.

I need to be able to type @user.subscribers and @user.subscriptions.

So, the relationship in one sense is both ways by default. However, if @user1 subscribes to @user2, that does not mean @user2 is subscribed to @user1 howevver, @user2 can find @user1 via @user.subscribers.

I have seen Ryan Bates Railscast on Self-Referential Associations. However that creates 1 way self-joins. But I think that doesn't leave the fact that there can be two relationships between the parties.

However, I have also seen The Rails Guide on association foreign keys.

I realize I could probably the Ryan Bates way, and just build two relationships, but that seems wrong, but I fear that the second way won't allow one to be a subscriber and one to be a provider each way. What is the most "correct" way to go about this?

dewyze
  • 979
  • 1
  • 7
  • 21

1 Answers1

2

Don't over complicate things

class Subs < ActiveRecord::Base

    belongs_to :subscriber, :class_name => 'User'
    belongs_to :user

end

class User < ActiveRecord::Base

    has_many :subs
    has_many :subscribers, :through => :subs, :source => :subscriber
    has_many :subscriptions, :through => :subs, :source => :user
end

Obviously you have to set up the join model in your database. And that should do it.

OneChillDude
  • 7,856
  • 10
  • 40
  • 79
  • 1
    I think this is right with the names reversed. I think the user is the subscriber and the result is the subscription, but it works. Thanks! – dewyze Apr 12 '13 at 03:42