Search code examples
ruby-on-railsassociationsself-reference

Rails self referrential associations, how to determine mutual intersection?


I want to have friends/followers mechanzm, so I've created following DB structure:

user_id
friend_id   

I want to know what's the easiest and simplest way to determine (Rails-way) that following users are mutual friends?

user_id        friend_id
1              2
2              1

Solution

  • Try this:

    test_pair = [1,2]
    Friendship.where(user_id: test_pair, friend_id: test_pair).count == 2