Luís Lopes
Luís Lopes

Reputation: 453

Implement connections (FB-like) between users on a RoR app

I'm trying to implement a Self-Referential Association in order to achieve a connections list for a given user (like FB or linkedIn does).

All the tutorials around implement the "following/follower" model that is a bit diffrent from this one, so... let's get creative:

So besides the user table, I have a user_connections table with the fields:

And "modeled" it the following way:

User.rb:

  # Connections
  has_many :user_connections, foreign_key: 'requester_id' # people that i invited to connect to me
  has_many :user_inverse_connections, foreign_key: 'requested_id', class_name: 'UserConnection' # people that invited me to connect with them

  has_many :i_invited, source: :requester, through: :user_connections
  has_many :invited_me, source: :requested, through: :user_inverse_connections

  def connections
    i_invited.merge(invited_me)
  end

I tried to test this:

2.0.0-p247 :003 > u.connections
  User Load (84.3ms)  SELECT `users`.* FROM `users` INNER JOIN `user_connections` ON `users`.`id` = `user_connections`.`requester_id` INNER JOIN `user_connections` ON `users`.`id` = `user_connections`.`requested_id` WHERE `user_connections`.`requester_id` = 1 AND `user_connections`.`requested_id` = 1

But as may noticed, it didn't work out:

Mysql2::Error: Not unique table/alias: 'user_connections': SELECT users.* FROM users INNER JOIN user_connections ON users.id = user_connections.requester_id INNER JOIN user_connections ON users.id = user_connections.requested_id WHERE user_connections.requester_id = 1 AND user_connections.requested_id = 1

Am I doing this really the right way?

Furtherly, any tips on how I can achieve "connection" search for 2nd level and others?

Upvotes: 0

Views: 62

Answers (2)

Luís Lopes
Luís Lopes

Reputation: 453

def connections
   i_invited + invited_me
end

This solved the problem...

But with a pay-off: (haven't tested yet, but I think) it's an array instead of a relation..

Upvotes: 0

Sam
Sam

Reputation: 2761

You can make a table with attributes follower_id, follows_id

And just record who every user follows in that table. This is a Many-Many relationship So John can be following Jane even though Jane does not follow John.

Upvotes: 1

Related Questions