【问题标题】:Rails, self-referential association on the User model to define friends/followersRails,用户模型上的自引用关联以定义朋友/关注者
【发布时间】:2011-12-13 23:14:17
【问题描述】:
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-3
【解决方案1】:
假设友谊的两个参与者也可能有其他友谊,那么你需要在某个地方存储这个特定友谊的状态。这表明您需要一个可以通过 has_and_belongs_to_many 获得的连接模型。然后您的状态可以存储在联接表中(在这种情况下为友谊)
class Person< ActiveRecord::Base
has_many :friendships
has_many :friends, :class_name => "Person", :through => :friendships
end
class Friendship < ActiveRecord::Base
belongs_to :friend1, :class_name => "Person"
belongs_to :friend2, :class_name => "Person"
end
但正如您可能从笨拙的朋友 1 和朋友 2 中注意到的那样,您即将遇到的问题是您可能希望将友谊视为一种非定向关系。
这是一个太大的话题,无法在此处详细介绍,但这里有一个地方解决了:
a promising looking article that I haven't actually used
最后请注意,虽然友谊是双向的,但友谊请求不是——在请求的情况下,您需要知道是谁发出了它,谁收到了它。所以我猜你会想要一个双向的友谊关系和一个定向的friend_request关系。当请求被批准后,该关系被删除,您添加双向友谊。