Brian Weinreich
Brian Weinreich

Reputation: 7702

Not sure how to convert SQL to Rails ActiveRecord

I run this SQL statement

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

Users Table
id | name | email

Friendships Table
user_id | friend_id

Checkins Table
user_id | checkin_time

I've tried

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

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

Any ideas on how to rewrite this with Active Record? I feel like there should be a simple way to pull this out...

Upvotes: 1

Views: 542

Answers (1)

Chris Bailey
Chris Bailey

Reputation: 4136

How about:

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

or, for something more like your original idea:

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

Upvotes: 2

Related Questions