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?