Rails,用户模型上的自引用关联来定义朋友/关注者 [英] Rails, self-referential association on the User model to define friends/followers

查看:35
本文介绍了Rails,用户模型上的自引用关联来定义朋友/关注者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个友谊协会.我发现并一直在关注教程:

I'm trying to create a friendship association. I found and have been following the the tutorial:

http://railscasts.com/episodes/163-self-referential-association

教程的问题是没有状态的概念(Accept,Pending,Ignored)

The problem with the tutorial is there is not concept of status (Accept,Pending,Ignored)

关于如何创建这种类型的关系但有一个状态的任何想法,所以当你的朋友请求它是待处理的,直到正确的用户接受或忽略?

Any ideas on how to create this type of relationship but have a status, so when you friend request it is pending until the correct user either accepts or ignores?

谢谢

推荐答案

假设好友中的双方可能还有其他好友,那么您需要某个地方来存储此特定好友的状态.这表明您需要一个可以通过 has_and_belongs_to_many 获得的连接模型.然后你的状态可以存储在连接表中(在这种情况下是Friendship)

Assuming that the both participants in the friendship might also have other friendships, then you need somewhere to store state of this particular friendship. That is an indication that you need a join model which you can get through a has_and_belongs_to_many. Then your status can be stored in the join table (Friendship in this case)

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 中注意到的那样,你即将遇到的问题是你可能希望友谊是一种非定向关系.

But as you might notice from the kludgy friend1 and friend2, the issue you are about to hit is that you probably want Friendship as a non directed relationship.

这是一个太大的话题,无法在此处详述,但这里有一个地方可以解决:一篇我还没有实际使用过的很有前途的文章

That's a too big a topic to detail here, but here's one place it's addressed: a promising looking article that I haven't actually used

最后请注意,虽然友谊是双向的,但友谊请求不是--在请求的情况下,您需要知道谁发出了它,谁收到了它.所以我猜你会想要一个双向的友谊关系和一个定向的朋友请求关系.请求获得批准后,该关系将被删除并添加双向友谊.

Then finally note that while a friendship is bi-direction, a friendship request is not--in the case of a request you need to know who issued it and who received it. So I'd guess you'll want a bi-directional friendship relationship and a friend_request relationship which is directed. When the request is approved that relationship is removed and you add the bi-directional friendship.

这篇关于Rails,用户模型上的自引用关联来定义朋友/关注者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆