1

There are a few questions similar to mine, but not quite what I'm looking for

rails many to many self join

Many-to-many relationship with the same model in rails?

My situation is something like User with many Friends.

class User
  has_many connections
  has_many friends, through: connections, class_name: 'User'
end

class Connection
  belongs to :user
  belongs to :friend, class_name: 'User'
end

This gets me pretty close, I can do:

first = User.create
second = User.create

first.friends << second
first.friends # => [ second ]

I would like the connection to go both ways

first.friends << second
second.friends # => [ first ]

The problem is that the "friends" query is looking in connections for the user_id of the User, and then finding all of the friend_ids. Since there is no connection with a user_id of "second", "second" has no connections.

I am thinking two solutions. 1) Create another connection with user_id = "second" when the first connection is created. 2) override the "friends" method to produce a SQL query that will figure it out.

Any thoughts about this? Thanks.

Community
  • 1
  • 1
Carl
  • 993
  • 8
  • 14
  • Sorry I don't have time for a full answer but you may find this to be helpful for your situation. http://railscasts.com/episodes/163-self-referential-association – Harry Mar 25 '14 at 15:47

1 Answers1

0

You can do it like this

first.friends << second
second.friends << first

by this you will have both or you can make a second relation rayn style

khaled_gomaa
  • 3,382
  • 21
  • 24