Find query

Hi,

I have user table (last_activity, last_activity_at, …) and
friendships table (many to many).
What I am trying to do is to show to the user the last actions of
his/her friends.

@activities = User.find_by_username(username, :order => 'last_activity_at DESC', :include => [:friendships => :friend])

<%= render :partial => 'friends_activity', :collection => @activities.friendships %>

But the descending ordering is not working :frowning: What I am missing here?
Cheers, Pete

On 1 Dec 2008, at 08:48, Petr B. wrote:

<%= render :partial => 'friends_activity', :collection => @activities.friendships %>

But the descending ordering is not working :frowning: What I am missing here?
Cheers, Pete

That sort would have ordered the users (from the ‘main’ find) by
descending last_activity_at, not the associations (which are loaded
with a separate find)

Fred

That sort would have ordered the users (from the ‘main’ find) by
descending last_activity_at, not the associations (which are loaded
with a separate find)

Fred

Ohh I see, I was trying to sort friendships table, but there is no
column last_activity_at. I guess that’s it. :frowning: or is there a way to
re-sort the data by last_activity_at ? Cheers

I’d write the above query like this:
u = User.find_by_username …
u.friendships.find :all, :joins => :friends, :order =>
‘last_activity_at desc’

Cheers Fred, this is the trick I was looking for.
Petr

On Dec 1, 9:47 am, Petr B. [email protected]
wrote:

That sort would have ordered the users (from the ‘main’ find) by
descending last_activity_at, not the associations (which are loaded
with a separate find)

Fred

Ohh I see, I was trying to sort friendships table, but there is no
column last_activity_at. I guess that’s it. :frowning: or is there a way to
re-sort the data by last_activity_at ? Cheers

The old style include that did one big join would probably do that for
you.
Just to be sure - I’m assuming that friendships and friends are a
self referential has many though relationship (ie back to users ?)

I’d write the above query like this:
u = User.find_by_username …
u.friendships.find :all, :joins => :friends, :order =>
‘last_activity_at desc’

You could squish that down to one query, but you’ll have to work out
how it aliases the table names (I always have to look that one up)

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs