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 %>

<%=h person.name %> <%=h person.items.count %> <% 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?

On Mon, Mar 9, 2009 at 11:42 AM, Sandy T.
[email protected] wrote:

@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 D.
http://destiney.com/

Greg D. wrote:

On Mon, Mar 9, 2009 at 11:42 AM, Sandy T.
[email protected] wrote:

@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 D.
http://destiney.com/

Cheers for that Greg, it works fine but is a little heavy on the
database (predictable I guess). However, this has steered me towards
creating a counter cache in the people table, which I hadn’t considered
before and which cuts down hugely on the number of SQL queries.

Thanks!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs