One option is to put each of the names as arguments for individual INNER JOINS. In SQL, it will be something like this:
SELECT users.* FROM users INNER JOIN friends AS f1 ON users.id = f1.user_id AND f1.name = 'Joe' INNER JOIN friends AS f2 ON users.id = f2.user_id AND f2.name = 'Jack'
Since this is INNER JOINS, it will display only those results in which the user table can be joined with both f1 and f2.
And use it in Rails, maybe do it something like this:
class User < AR has_many :friends def self.who_knows(*friend_names) joins((1..friend_names.length).map{ |n| "INNER JOIN friends AS f#{n} ON users.id = f#{n}.user_id AND f#{n}.name = ?" }.join(" "), *friend_names) }) end end
which you can then call as follows:
@users = User.who_knows("Joe", "Jack")
Danne mann
source share