# Sorting with related tables

**URL:** <https://www.ruby-forum.com/t/sorting-with-related-tables/192261>\
**Category:** Rails\
**Created:** [July 27, 2010, 10:01am UTC](https://www.ruby-forum.com/t/sorting-with-related-tables/192261 "2010-07-27T10:01:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mohammed\_a](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/bcef8e/32.png) [@mohammed\_a](https://www.ruby-forum.com/u/mohammed_a)\
**Post date:** [July 27, 2010, 10:01am UTC](https://www.ruby-forum.com/t/sorting-with-related-tables/192261/1 "2010-07-27T10:01:47Z")

</div>

Hi  
I have two tables: users and tickets. A user has many tickets which is  
defined in the model. I want to order the users based on the number of  
tickets they have. What is the easiest way to do it in Rails without  
writing to many SQL statements.

---

<div class="post-metadata">

**Author:** ![mohammed\_a](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/bcef8e/32.png) [@mohammed\_a](https://www.ruby-forum.com/u/mohammed_a)\
**Post date:** [July 27, 2010, 5:53pm UTC](https://www.ruby-forum.com/t/sorting-with-related-tables/192261/2 "2010-07-27T17:53:39Z")

</div>

On 27 July 2010 08:59, Mohammed A. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Hi  
> I have two tables: users and tickets. A user has many tickets which is  
> defined in the model. I want to order the users based on the number of  
> tickets they have. What is the easiest way to do it in Rails without  
> writing to many SQL statements.

Look at adding a “counter cache” column to your User model to store  
the amount of tickets associated to them. Then you can just use that  
column to sort by in a normal find.

[http://rails.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html](http://rails.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html)
