views:

27

answers:

1

In my Rails app, a user can subscribe to other users. One should be able to get a user's subscriptions and subscribers from a user instance.

Right now, I have a User model and a Subscription model. Subscription is the join model (joining User to User) in a two-way self-referential has_many :through relationship.

Subscription:

class Subscription < ActiveRecord::Base
  belongs_to :from_user, :class_name => 'User'
  belongs_to :to_user, :class_name => 'User'
end

User:

class User < ActiveRecord::Base
  ...
  has_many :subscriptions_as_subscriber, :foreign_key => 'from_user_id', :class_name => 'Subscription', :dependent => :destroy
  has_many :subscriptions_as_subscription, :foreign_key => 'to_user_id', :class_name => 'Subscription', :dependent => :destroy
  has_many :subscribers, :through => :subscriptions_as_subscription, :source => :from_user
  has_many :subscriptions, :through => :subscriptions_as_subscriber, :source => :to_user
  ...
end

First question: Would I be better served by a different setup?

Second question: How might I create controller(s) to create and destroy Subscriptions and to access a User's subscriptions and subscribers?

Right now, I have a SubscriptionsController with create and destroy actions, and subscriptions and subscribers actions in my UsersController. However, I'm wondering if there isn't a better (more RESTful?) way to do this. Accesssing a user's subscriptions and subscribers through the index action on SubscriptionsController, perhaps?

+1  A: 

I would recommend awesome_nested_set from collective_idea. It is a breeze to implement and should give you the functionality you are looking for.

Here is a post with some details on implementation that you can borrow from: http://www.justinball.com/2009/01/18/heirarchies-trees-jquery-prototype-scriptaculous-and-acts_as_nested_set/

UPDATE:

I would see this setup as a tree:

Subscriber
 + subscription
   + subscription
     + subscription
   + subscription
   + subscription
 + subscription
Geoff Lanotte
Thanks, Geoff. Unfortunately, I don't think this will help me. This looks to be useful for building trees (say, for hierarchical comments), but not for my scenario. Maybe I'm missing something.
Nick