如何在Rails中建立共同的友谊 [英] How to model a mutual friendship in Rails

查看:91
本文介绍了如何在Rails中建立共同的友谊的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题是在Stack Overflow上问过的,但是答案并没有以我能解释的方式为我解决.我的一般方法受到教程的启发.

I know this question has been asked before on Stack Overflow, but the answers aren't doing it for me in ways I can explain. My general approach was inspired by this tutorial.

我想做的是创建一个非常简单的模型来与用户建立友谊,从而通过一条记录在两端建立等效的友谊.

What I'm trying to do, is create a really simple model for friending users that creates an equivalent friendship on both ends with a single record.

在数据库级别,我只有一个'friendships'表,其中只有一个user_id,friend_id和is_pending布尔列.

At the db level, I just have a 'friendships' table that just has a user_id, a friend_id, and an is_pending boolean column.

在user.rb中,我将关系定义为:

In user.rb I've defined the relationship as:

has_many :friendships
has_many :friends, through: :friendships

在friendship.rb中,我将这种关系定义为:

In friendship.rb, I've defined the relationship as:

belongs_to :user
belongs_to :friend, :class_name => 'User'

如果我添加了友谊,则可以按以下方式访问:

If I add a friendship, I can access as follows:

> a = User.first
> b = User.last
> Friendship.new(a.id, b.id)
> a.friends
=> #<User b>

那是完美的,但是我想要的也是能够朝着另一个方向前进:

That's perfect, but what I want is to also be able to go in the other direction like so:

> b.friends

不幸的是,按原样定义的关系,我得到了一个空集合.运行的SQL表明它正在搜索user_id =b.id.如何指定它也应该搜索friend_id = b.id?

Unfortunately, with the relationship defined as it is, I get an empty collection. The SQL that runs shows that it's searching for user_id = b.id. How do I specify that it should also search for friend_id = b.id?

推荐答案

也许是这样:

friendship.rb
belongs_to :friend_one, :foreign_key => :user_id
belongs_to :friend_two, :foreign_key => :friendship_id

user.rb

has_many :friendship_ones, :class_name => 'Friendship', :foreign_key => :friendship_id
has_many :friend_ones, through: :friendship_ones
has_many :friendship_twos, :class_name => 'Friendship', :foreign_key => :user_id
has_many :friend_twos, through: :friendship_twos


def friends
  friend_ones + friend_twos
end

您有两个查询来查找朋友,但这是一个简单的数据模型,您只需调用@ user.friends来查找实例.

You get two queries to find the friends, but it is a simple data model and you you do just call @user.friends to find the instances.

如果您同时加载了两个friend_ones和friend_twos关联,则渴望加载.

It would be amenable to eager loading, if you load the two friend_ones and friend_twos associations.

这篇关于如何在Rails中建立共同的友谊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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