ruby on rails getting a 2-way friend relationship in active record?

时间秒杀一切 提交于 2019-12-08 00:32:29

问题


Im trying to figure out how to do a mutual 2-way relationship, that is:

user_id  friend_id
  1          2
  2          1

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?


回答1:


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

Example is from §4.4.2.1.




回答2:


Read the final chapter of Micheal Heartl Ruby on Rails Tutorial: Learn Rails by Example where he explains these kind of examples really well. There is a free online edition here.

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

Take a look at the final chapter. I hope it helps.



来源:https://stackoverflow.com/questions/9671829/ruby-on-rails-getting-a-2-way-friend-relationship-in-active-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!