views:

19

answers:

2

I'm working on a social networking application and am trying to build a complex query that efficiently pulls all of a users' friends' checkins from the database. Basically I need: "user.friends.checkins"

I've recreated (in simplified form) the data structure below for reference and included several solutions I've found, however I feel like my solutions are sub-optimal. I'm hoping that someone can point out a better way... So here goes:

I tried this first, which works, but is way too slow given that users typically have +1000 friends each:

=> Checkin.where(:user_id => self.friends)

Then I tried this, which also works and is much faster, but feels sloppy:

=> Checkin.joins(:user).joins('INNER JOIN "friendships" ON
"users"."id" = "friendships"."friend_id"').where(:friendships =>
{:user_id => 1})

Any help you can provide would be GREATLY appreciated! Thanks in advance!!!

=== Data structure ===

Users table has columns: id, name
Friendships table has columns: user_id, friend_id
Checkins table has columns: id, location, user_id

=== Models ===

class User
 has_many :friendships
 has_many :friends, :through => :friendships
 has_many :checkins
end

class Friendship
 belongs_to :user
 belongs_to :friend, :class_name => 'User'
end

class Checkin
 belongs_to :user
end
A: 

The first query should serve you well. Add indexes to the foreign key fields in the query.

Steve DeWald
The problem with the first solution is that it takes 3 seconds to load the 500-1000 ActiveRecord objects that are returned by "self.friends". It's not SQL that is slow (the SQL only takes 2-3ms), it's ActiveRecord. I just posted another solution that I've uncovered that seems to be an improvement.
Matt Hodan
A: 

Best solution I've found so far:

Checkin.joins(:user => :friendships).where('friendships.friend_id' => self.id)
Matt Hodan