There are a few questions similar to mine, but not quite what I'm looking for
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.