# Order by distantly related table

**URL:** <https://www.ruby-forum.com/t/order-by-distantly-related-table/145043>\
**Category:** Rails\
**Created:** [August 5, 2008, 3:25pm UTC](https://www.ruby-forum.com/t/order-by-distantly-related-table/145043 "2008-08-05T15:25:24Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![mikej](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/a9a28c/32.png) [@mikej](https://www.ruby-forum.com/u/mikej)\
**Post date:** [August 5, 2008, 3:25pm UTC](https://www.ruby-forum.com/t/order-by-distantly-related-table/145043/1 "2008-08-05T15:25:24Z")

</div>

I have 2 tables (toms and dicks) joined with has\_many through a third  
table (harries). Table tunnels is related to table dicks (table  
tunnels has many dicks).

I would like to select a record from toms with all related records  
from dicks ordered a field in tunnels.

Something like:

@tom = Tom.find(1, :include =\> :dick.tunnels, :order\_by =\>  
tunnel.length)

Any ideas?

Mike

---

<div class="post-metadata">

**Author:** ![mikej](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/a9a28c/32.png) [@mikej](https://www.ruby-forum.com/u/mikej)\
**Post date:** [August 5, 2008, 3:35pm UTC](https://www.ruby-forum.com/t/order-by-distantly-related-table/145043/2 "2008-08-05T15:35:29Z")

</div>

I’m not 100% ssure about the syntax for eager loading of distant  
tables,  
but it should look something like that:

@tom = Tom.find(1, :include =\> {:dicks =\> [:tunnels]}, :order\_by =\>  
“tunnels.length ASC”)

could be, the {} should be []

---

<div class="post-metadata">

**Author:** ![mikej](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/a9a28c/32.png) [@mikej](https://www.ruby-forum.com/u/mikej)\
**Post date:** [August 5, 2008, 3:36pm UTC](https://www.ruby-forum.com/t/order-by-distantly-related-table/145043/3 "2008-08-05T15:36:05Z")

</div>

On 5 Aug 2008, at 14:20, Thorsten Müller wrote:

> I’m not 100% ssure about the syntax for eager loading of distant  
> tables,  
> but it should look something like that:
> 
> @tom = Tom.find(1, :include =\> {:dicks =\> [:tunnels]}, :order\_by =\>  
> “tunnels.length ASC”)

That’ll do it, but there’s no need to use include, joins will do just  
fine i.e.

@tom = Tom.find(1, :joins =\> {:dicks =\> :tunnels}, :order\_by =\>  
“tunnels.length ASC”)

Fred

---

<div class="post-metadata">

**Author:** ![mikej](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/a9a28c/32.png) [@mikej](https://www.ruby-forum.com/u/mikej)\
**Post date:** [August 5, 2008, 3:44pm UTC](https://www.ruby-forum.com/t/order-by-distantly-related-table/145043/4 "2008-08-05T15:44:18Z")

</div>

Thanks very much. Final solution:

@tom = Tom.find(1, :joins =\> {:dicks =\> :tunnel}, :order =\>  
“tunnels.length ASC”)

(tunnels singular).

Mike

On Aug 5, 2:30 pm, Frederick C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
