I have the following models for my user:
class User < ActiveRecord::Base
has_many :facebook_friendships
has_many :facebook_friends, :through => :facebook_friendships, :source => :friend
def mutual_facebook_friends_with(user)
User.find_by_sql ["SELECT users.* FROM facebook_friendships AS a
INNER JOIN facebook_friendships AS b
ON a.user_id = ? AND b.user_id = ? AND a.friend_id = b.friend_id
INNER JOIN users ON users.id = a.friend_id", self.id, user.id]
end
end
class FacebookFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
end
If user ID 53 and user ID 97 are friends with each other, you will have the rows [53, 97] and [97, 53] in the facebook_friendships table in the database. Here is the raw sql query that I came up with to make mutual friends:
SELECT users.* FROM facebook_friendships AS a
INNER JOIN facebook_friendships AS b
ON a.user_id = :user_a AND b.user_id = :user_b AND a.friend_id = b.friend_id
INNER JOIN users ON users.id = a.friend_id
I would mutually_other_with return a relation instead of an array. Thus, I could associate the result with other conditions, for example, where (college: "NYU") and get all the benefits of ActiveRecord. Is there a good way to do this?
source
share