我的代码就是这个
user_friends =Friend.find(:all, :select => "friend_id", :conditions => "app_user_id =12345")
second_user_friends = Friend.find(:all, :select => "friend_id", :conditions => "app_user_id = 123321")
common_friends_id = user_friends.map{|uf| uf.friend_id}.to_a & second_user_friends.map{|suf| suf.friend_id}.to_a
common_friends = Friend.find(:all, :conditions => "friend_id in (#{common_friends_id.join(",")})
and app_user_id = 12345")
我需要花很多时间才能帮助我
答案 0 :(得分:1)
<强>尝试强>
ActiveRecord::Base.connection.select_all("SELECT f1.* FROM friends f1
JOIN friends p2 ON f2.friend_id = f1.friend_id
WHERE f1.app_user_id = 12345 and f2.app_user_id = 123321")
对于Rails 2
Friend.all(:joins=>"JOIN friends f2 ON f2.friend_id = friends.friend_id",
:conditions =>"friends.app_user_id = 12345 and f2.app_user_id = 123321")
对于Rails 3
Friend.where("friends.app_user_id = 12345 and f2.app_user_id = 123321")
.joins("JOIN friends f2 ON f2.friend_id = friends.friend_id")
答案 1 :(得分:0)
我认为这应该足够了。
second_user_friend_ids = Friend.find(:all, :select => "friend_id", :conditions => "app_user_id = 123321").map(&:id)
common_friends = Friend.find(:all, :conditions => "friend_id in (#{second_user_friend_ids.join(",")}) and app_user_id = 12345")