不确定如何将SQL转换为Rails ActiveRecord

时间:2012-03-30 16:56:11

标签: mysql sql ruby-on-rails activerecord

我运行此SQL语句

select * from checkins where user_id in (SELECT friend_id from friendships where user_id=1);

用户表 id |名字|电子邮件

友谊表 user_id | friend_id

签入表 user_id | checkin_time

我试过

friends = Friendship.select("friend_id").where("user_id = 1");

Checkin.where("user_id = "+friends);

有关如何使用Active Record重写此内容的任何想法?我觉得应该有一个简单的方法来解决这个问题......

1 个答案:

答案 0 :(得分:2)

怎么样:

Checkin.joins("INNER JOIN friendships ON friendships.friend_id = checkins.user_id).where('friendships.user_id = ?', 1)

或者,更像您最初的想法:

friends = Friendship.select("friend_id").where("user_id = 1").map { |f| f.friend_id };
Checkin.where(:user_id => friends);