I have a Topic model and a Post model. A Topic has many Posts, and A Post belongs to Topic.
I want to display index page of Topic based on the most recent Post for each Topic. More recent the last Post is for a Topic, it will be displayed more at the top. I am basically hoping to simulate what regular forums do. If you reply to a topic, the topic rises up in index page.
So I need to somehow order topics based on *created_at* of the last post for each topic. How can this be done?
topics_controller.rb
def index
@forum = Forum.find(params[:forum_id])
@topics = @forum.topics.find(:all, :order => "last_post_id DESC")
# last_post_id is a column of Topic that stores ID of the last post
end
post.rb
class Post < ActiveRecord::Base
belongs_to :topic
attr_accessible :content
end
topic.rb
class Topic < ActiveRecord::Base
has_many :posts, :dependent => :destroy
belongs_to :forum
accepts_nested_attributes_for :posts, :allow_destroy => true
attr_accessible :name, :last_post_id, :posts_attributes
end
What about Topic.includes(:posts).order(‘posts.created_at DESC’)