开发者

Rails two-way self-referential has_many :through -- controller setup?

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, :t开发者_如何学Pythonhrough => :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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜