Forum: Ruby on Rails order by number of occurances in a has_many relationship

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
08dc0d8ec98b1228792637b29a2427a7?d=identicon&s=25 Sandy Thomson (rhubarbcrumble)
on 2009-03-09 17:42
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?
Aad37b5f7116c8d1f547d23b37566032?d=identicon&s=25 Greg Donald (destiney)
on 2009-03-09 18:03
(Received via mailing list)
On Mon, Mar 9, 2009 at 11:42 AM, Sandy Thomson
<rails-mailing-list@andreas-s.net> 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 Donald
http://destiney.com/
08dc0d8ec98b1228792637b29a2427a7?d=identicon&s=25 Sandy Thomson (rhubarbcrumble)
on 2009-03-09 19:00
Greg Donald wrote:
> On Mon, Mar 9, 2009 at 11:42 AM, Sandy Thomson
> <rails-mailing-list@andreas-s.net> 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 Donald
> 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 topic is locked and can not be replied to.