Hello all,

I'm currently working on a little forum app to learn rails.
In a category all topics have to be listed. How can I sort the topics by the date of the last post?

My models:

Code Ruby:
class Category < ActiveRecord::Base
  has_many :topics  
end
 
class Topic < ActiveRecord::Base
  belongs_to :category
  has_many :posts
end
 
class Post < ActiveRecord::Base
  belongs_to :topic
end

In my topics table there is a field last_post_id.

My controller:

Code Ruby:
class CategoryController < ApplicationController
  def show
    category_id = params[:id]
 
    @category = Category.find(category_id)
 
    sql = "topics.*, 
           (SELECT posts.created_at 
              FROM posts
             WHERE posts.id = topics.last_post_id)
           AS last_post_time"
    @topics = Topic.find(:all,
                         :select     => sql,
                         :conditions => {:category_id => category_id},
                         :order      => 'last_post_time DESC')
  end
end

That`s ugly. @category allready contains the all topics. Beside that I would like to avoid mixing SQL with Ruby. And I think such a query should be in a model.

Could anyone show me a better way?

oerdec