5

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

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

这似乎是一种非常不优雅的方式来做到这一点。我想知道是否有人有更好的想法?也许是我没看到的更类似 Rails 的东西?

4

2 回答 2

8

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

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

于 2011-01-18T18:03:34.933 回答
1

你可以使用这个实现:

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
于 2011-01-18T18:05:16.303 回答