Ruby on Rails的获得在活动记录一个2路的朋友关系? [英] ruby on rails getting a 2-way friend relationship in active record?
本文介绍了Ruby on Rails的获得在活动记录一个2路的朋友关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试着去弄清楚如何做一个相互2路的关系,那就是:
Im trying to figure out how to do a mutual 2-way relationship, that is:
user_id friend_id
1 2
2 1
在上面的用户1和用户2会成为朋友,如果两个 USER_ID = 1
的 friend_id = 2
和 friend_id = 2
的 USER_ID = 2
因为有朋友在表格中。如何计数的ActiveRecord所有的2路相互之间的关系?
In above user 1 and user 2 would be friends if both user_id = 1
has friend_id = 2
and friend_id = 2
has user_id = 2
as there friend in a table. How to count all the 2-way mutual relations in ActiveRecord?
推荐答案
您要查找的内容是的 has_and_belongs_to_many
关系:
What you're looking for is a has_and_belongs_to_many
relationship:
class User < ActiveRecord::Base
has_and_belongs_to_many :friends, :class_name => "User",
:foreign_key => "this_user_id",
:association_foreign_key => "other_user_id"
end
例是从<一个href="http://guides.rubyonrails.org/association_basics.html#has_and_belongs_to_many-association_foreign_key"相对=nofollow>§4.4.2.1。
这篇关于Ruby on Rails的获得在活动记录一个2路的朋友关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文