我有2个型号
class User < AR has_many :friends end class Friend < AR # has a name column end
我需要找到所有与’Joe’和’Jack’都是朋友的用户
知道我怎么能在铁轨上做到这一点?
解决方法
一种选择是将每个名称作为单个INNER JOINS的参数.在sql中它将是这样的:
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'
因为它是INNER JOINS,所以它只显示用户表可以用f1和f2连接的结果.
要在Rails中使用它,也许可以这样做:
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
你可以这样打电话:
@users = User.who_knows("Joe","Jack")