Dynamic Finders and Count

Hi!

I have a (hopefully) simple problem, but just don’t get the idea how
to implement it in rails.

There are two classes, one for users and one for comments. A user
has_many comments and each comment belongs_to user.

I tried to do something like this:

@foo = User.find(:all, :order => ‘comments_count’)

comments_count is not known. An :include => ‘comments’ also doesn’t
help (even that the SQL Syntax is doing a join now).

How can I find all Users sorted by the number of comments they have
posted? It’s enough if the resulting list only contains the count-
field as result. It is not necessary to have all comments “attached”
to the list.

Thanks in advance!
Markus

On 26 Oct 2007, at 10:13, lordbyte wrote:

How can I find all Users sorted by the number of comments they have
posted? It’s enough if the resulting list only contains the count-
field as result. It is not necessary to have all comments “attached”
to the list.

Off the top of my head, something like this will do the job
User.find :all, :select => ‘users., count() as comment_count’,
:joins => ‘inner join comments on comments.id = comment_id’,
:group => ‘users.id’,
:order => ‘comment_count’

Fred

lordbyte wrote:

I tried to do something like this:

@foo = User.find(:all, :order => ‘comments_count’)

comments_count is not known. An :include => ‘comments’ also doesn’t
help (even that the SQL Syntax is doing a join now).

There is no column named comments_count therefore the problem you are
getting. What you could do is use a counter cache. Then your query
would work as is.

Eric

Hi!

There is no column named comments_count therefore the problem you are
getting. What you could do is use a counter cache. Then your query
would work as is.

That’s great - exactly what I searched! :slight_smile:

Thanks for help!
Markus