views:

44

answers:

2

Hi,

I have a User model which has friends (User.friends with a user_id/friend_id join table called followings). Each user has events (the events table has a user_id column).

For an activity feed, I want to get an array with the last 20 events of the friends of the user. Right now I'm calling the last 20 events for each friend, sorting everything by date and just keeping the last 20 events.

How can I do that directly into the database so that I only need one request instead of one per friend?

Is there a way I can do that directly with Rails? Or should I use an SQL request?

Thank you,

Kevin

+1  A: 
select e.* from
(select rownum r , e.* from events e where user_id in (our target friends) order by date desc)    
where r < 20 ;

I don't know if rownum is called 'rownum' in postgres. rownum - is number of row. if e.* is not working, try to write every field manually. out target friends is smth like select user_id2 from friend_connections where user_id1 = targetId union select user_id1 from friend_connections where user_id2 = targetId. Yes, i understand that is is very ugly.

foret
+1  A: 

I'd do it in a SQL request like this:

select Events.Summary from Events
join Followings
    on Events.User_Id = Followings.Friend_Id
where Followings.User_Id = @User_Id
order by Events.Date desc
limit 20;

limit 20 is MySql - is it the same in PostgreSql?

Paul Spangle
Yes, "limit 20" will work in PostgreSql as well.
Tim
Great!And let say I don't want a special kind of Events which is specified in its attributes, would something like this work?"select Events.Summary from Events where Events.kind != not_that_kind join Followings …"
Kevin
You'd have to put that in the WHERE clause. eg. `where Followings.User_Id = @User_Id and Events.kind <> not_that_kind`.
Paul Spangle
But, depending on how many kinds you have, it might be easier to say `and Events.kind not in (1, 5, 23)...`
Paul Spangle