How to achieve concept of connection list with minimal cost using rails ActiveRecord?

44 views Asked by At

Say User A is connected to B, then user B is automatically considered to be connected with user A.

User has_many connection

Connection Table:

id, user_id, connected_user_id

Say


id || user_id|| connected_user_id

1 || 1 || 2

2 || 3 || 1

3 || 2 || 3



Expected outcome:

User.find(1).connections

[< User id:2, ... >,< User id:3, ... > ]

User.find(2).connections

[< User id:1, ... >, < User id:3, ... >]

1

There are 1 answers

8
CChandler81 On

If you need a many-to-many relationship, which it sounds like you do, you can set up a has_many through relationship:

class User < ApplicationRecord
  has_many :connections
  has_many :connected_users, through: :connections
end

class Connection < ApplicationRecord
  belongs_to :user
  belongs_to :connected_user, class_name: "User"
end

Then to find all connections like you want you can create a method in your User class:

def get_connections
  User.find(Connection.where(user_id: self.id).connected_user_ids + Connection.where(connected_user_id: self.id).user_ids)
end

User.find(1).get_connections should return

[< User id:2, ... >,< User id:3, ... > ]