ruby on rails在活跃记录中获得双向朋友关系?

我试图弄清楚如何做一个相互的双向关系,即:

user_id friend_id 1 2 2 1 

在上面的用户1和用户2将是朋友,如果user_id = 1都具有friend_id = 2并且friend_id = 2具有user_id = 2作为表中的朋友。 如何计算ActiveRecord中的所有双向相互关系?

您正在寻找的是has_and_belongs_to_many关系 :

 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 

示例来自§4.4.2.1 。

阅读Micheal Heartl Ruby on Rails教程的最后一章:通过示例学习Rails,他非常好地解释了这些示例。 这里有免费的在线版本。

https://www.railstutorial.org/book/following_users

看看最后一章。 我希望它有所帮助。