Rails中的自引用模型3

我有一个实体模型,我想显示实体之间的连接。 即,实体1连接到实体2。

我现在的想法是在两个名为Connection之间创建一个连接模型,让它像传统的rails连接表一样工作。 除了列为entity_one_id和entity_two_id之外,然后在Entity和Connection之间建立多对多关系。

这似乎是一种非常优雅的方式。 我想知道是否有人有更好的想法? 也许更多的东西,我只是没有看到?

这是最常见的方式。 如果实体仅连接到另一个模型,则可以使用链表,树状结构。

查看Ryan Bates关于自连模型的Railscast 。 它涉及类似社交网络的系统,但它仍然具有您需要的原则并提供了一个很好的起点

您可以使用此实现:

class User < ActiveRecord::Base has_many :friends, :through => :friendships, :conditions => "status = 'accepted'" has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at has_many :friendships, :dependent => :destroy end class Friendship < ActiveRecord::Base belongs_to :user belongs_to :friend, :class_name => "User" end