Rails双向自引用has_many:通过 – 控制器设置?
在我的Rails应用程序中,用户可以订阅其他用户。 一个人应该能够从用户实例获得用户的订阅和订阅者。
现在,我有一个User
模型和一个Subscription
模型。 Subscription
是双向自引用has_many :through
关系的连接模型(加入User
到User
)。
订阅:
class Subscription 'User' belongs_to :to_user, :class_name => 'User' end
用户:
class User '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
第一个问题:我可以通过不同的设置更好地服务吗?
第二个问题:我如何创建控制器来创建和销毁订阅以及访问用户的订阅和订阅者?
现在,我有一个SubscriptionsController
其中包含create
和destroy
操作,以及我的UsersController
subscriptions
和subscribers
操作。 但是,我想知道是否有更好的(更多RESTful?)方式来做到这一点。 也许通过SubscriptionsController
上的index
操作访问用户的订阅和订阅者?
我会推荐来自collective_idea的awesome_nested_set 。 实现起来轻而易举,应该为您提供所需的function。
这是一篇文章,其中包含一些可以借鉴的实施细节: http : //www.justinball.com/2009/01/18/heirarchies-trees-jquery-prototype-scriptaculous-and-acts_as_nested_set/
更新:
我会将此设置视为树:
Subscriber + subscription + subscription + subscription + subscription + subscription + subscription