【问题标题】:Rails two-way self-referential has_many :through -- controller setup?Rails 双向自引用 has_many:通过 -- 控制器设置?
【发布时间】:2010-06-24 00:50:17
【问题描述】:

在我的 Rails 应用中,用户可以订阅其他用户。应该能够从用户实例中获取用户的订阅和订阅者。

现在,我有一个User 模型和一个Subscription 模型。 Subscription 是双向自引用has_many :through 关系中的连接模型(将User 连接到User)。

订阅:

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

用户:

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

第一个问题:不同的设置会更好地为我服务吗?

第二个问题:我如何创建控制器来创建和销毁订阅以及访问用户的订阅和订阅者?

现在,我的UsersController 中有一个SubscriptionsControllercreatedestroy 操作,以及subscriptionssubscribers 操作。但是,我想知道是否没有更好(更 RESTful?)的方法来做到这一点。也许通过SubscriptionsController 上的index 操作访问用户的订阅和订阅者?

【问题讨论】:

  • has_and_belongs_to_many 关系应该是最好的 imo。 HABTM 追随者,HABTM 追随者。

标签: ruby-on-rails


【解决方案1】:

我会推荐来自collective_idea 的awesome_nested_set。实现起来轻而易举,并且应该为您提供所需的功能。

这里有一个关于实现细节的帖子,你可以借鉴:http://www.justinball.com/2009/01/18/heirarchies-trees-jquery-prototype-scriptaculous-and-acts_as_nested_set/

更新:

我会将此设置视为一棵树:

Subscriber
 + subscription
   + subscription
     + subscription
   + subscription
   + subscription
 + subscription

【讨论】:

  • 谢谢,杰夫。不幸的是,我认为这对我没有帮助。这看起来对构建树很有用(例如,对于分层 cmets),但不适用于我的场景。也许我错过了什么。
猜你喜欢
  • 2019-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多