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
columns...

@foo=Foo.find(1)
@foo.bar.last.whatever

But lets say I have much foo

@foos=Foo.find(:all)
@foos.each do | f |
f.bar.last.whatever
end

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 = ?", @group.id], :order => "what in the world do i put
here...")

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 topic.post.last

Any great ideas?

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

---A

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

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
one.

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:

---A