How to sort on a join... kindof.

So i've got two models:

foo has_many bars
bar belongs_to foo

And then I can find the newest bar since I'm using nifty created_at


But lets say I have much foo

@foos.each do | f |

But what I really want to do is sort the foos in order of the last bar
created for each foo. But I can't figure out how to do it. The
specifics are topics and posts, and of course I'm trying to do a
paginating find...

    @topics_pages, @topics = paginate(:topics, :conditions =>
["group_id = ?",], :order => "what in the world do i put

It's almost like I have to do a join in sql here, but then I end up
pulling in all the posts in to the array at the time of the find, when
all I want to do is get the topic so I can later do a

Any great ideas?

OK, so I think I can just get the topics into @topics, and then sort
the array in rails on, but I don't know how to do
it... am I going down the right path here?


More idiomatically:
  @things.sort_by {|x| x.created_at}.each do |thing|
    #loop through your things and display them

Ought to be quicker, but will use more memory.

----------------------------------------------------- Enumerable#sort_by
     enum.sort_by {| obj | block } => array

I'd rather do it in SQL, but I didn't think :order => "created_at"
would work... the data being pulled in is a list of topics. I do not
want to sort on the "created_at" of the topic, but on the "created_at"
of the last post associated with the topic.

Topic 1 was created 2 days ago. It has 2 posts, the newest post is 4
hours old.
Topic 2 was created 1 day ago. It has 2 posts, the newest post is 8
hours old.
Topic 3 was created 1 hour ago. It has 2 posts, the newest post is 30
minutes old.

The correct sort order should be 3, 1, 2. If I just do :order =>
"created_at" then the order will be 3, 2, 1.

I am using the .last function to find the last post, but of course
that only exists in rails. If I specify the post<->topic join in
the .find then I can do :order => "posts.created_at" but the side
effect of that is a huge array returned to rails with all the posts
for a particular topic, when all I need is the created_at of the .last

I think I'm looking at a sort in rails, after the list of topics has
been pulled from the db. Rails' .sort and sort_by do not make any
sense to me yet, so I'll have to do some reading and figure them
out. :slight_smile: