Sorting posts


I have a topic model which has_many replies.

On my topic index page I would like to be able to sort the topics by
the number of replies.

In my topic model I have defined

has_many :replies
  def total_replies

And in my controller I have tried

@topics = Topic.find(:all, :conditions => ["forum_id = ?",], :order => "total_replies DESC")

but I get the error Mcolumn "total_replies" does not exist

I know the column doesn't exist, but the question is, how can I get
the 'total_replies' to behave as a column.



I think that's you could use the counter_cache feature:

class AddReplyCount < ActiveRecord::Migration
  def self.up
    add_column :topics, :replies_count, :integer, :default => 0
    Topic.find(:all).each do |t|
      t.update_attribute(:replies_count, t.replies.length)

  def self.down
    remove_column :topics, :replies_count

class Topic < AR
  has_many :replies, :order => 'replies_count ASC'

class Reply < AR
  belongs_to :topic, :counter_cache => true

You can't - it's a method on a model, and the DB knows nothing about it.
But you can add a column that keeps the value of associated replies
and then the query will work. Rails will do this for you with a
(I'm still getting the hijacked domain, so I hope that's the right link)

Michael Pavling wrote: