order by number of occurances in a has_many relationship

I can't seem to find anything to explain how I might be able to order a list according to the number of occurrences of an item in a has_many relationship, so maybe someone could help me learn how...

To illustrate, imagine I have the following situation:

I have one table with details for a number of people, and one table of items. Each item belongs to one person and each person can have may items.

In my view I have something like this:

<% for person in @people %>   <tr>     <td><%=h person.name %></td>     <td><%=h person.items.count %></td>   </tr> <% end %>

I can get the list to order by the id/name etc. of the people, but I really want to order it by the number of items belonging to each person, something like so:

@people = Person.find(:all, :order => 'person.items.count desc')

except that this brings up an 'unknown column' error.

Any ideas for getting around this?

@people.sort!{ |a,b| a.items.count <=> b.items.count }

Greg Donald wrote: