I’m trying to set the order for Topic index by most recent Comment. This is working:
Topic.joins(:comments).order("comments.created_at desc")
But it lists the Topics more than one time.
Is there a way to limit the times each topic is displayed to one?
The most elegant way I found to solve the problem is to add
touchto the polymorphic association in the comment model:belongs_to :commentable, :polymorphic => true, touch: trueIf you’re not using a polymorphic association, you can use:
belongs_to :topic, touch: trueThen, all I had to do was change the default scope in the topic model to
updated_atdefault_scope order: 'topics.updated_at DESC'Adding
touchto comment means that every time a comment is added to topic, it updates the updated_at column in topics.In the controller I am using:
@topics = Topic.order(sort_column + " " + sort_direction).paginate(:per_page => 20, :page => params[:page])Topic.allor something else could work there as well.Thanks to my super friend Alain for pointing this out to me.