Rubytastic
Rubytastic

Reputation: 15501

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

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?

Upvotes: 2

Views: 1238

Answers (2)

Maddy
Maddy

Reputation: 1243

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.

Upvotes: 1

Andrew Marshall
Andrew Marshall

Reputation: 96994

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.

Upvotes: 2

Related Questions