# Eager loading optimization

**URL:** <https://www.ruby-forum.com/t/eager-loading-optimization/153375>\
**Category:** Rails\
**Created:** [November 15, 2008, 11:18pm UTC](https://www.ruby-forum.com/t/eager-loading-optimization/153375 "2008-11-15T23:18:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![indigoi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@indigoi](https://www.ruby-forum.com/u/indigoi)\
**Post date:** [November 15, 2008, 11:18pm UTC](https://www.ruby-forum.com/t/eager-loading-optimization/153375/1 "2008-11-15T23:18:02Z")

</div>

I have a phrase model, a definition model, and a children model  
a phrase has many definitions, a definition has many children

currently when i am doing a find i have an include that looks like

Phrase.find(:all,:include =\> [{:definitions =\> :children}] , :conditions  
=\> ‘foo’)

but for the most part I only want the first definition, and its  
associated children. The loading of all of the additional definitions  
and their associated children is killing my site load time (but not more  
than eliminating the :include all together).

Is there a way to get only the first definition under an associated  
phrase ( the definitions are ordered by rank) without having to write my  
own SQL ??

Rails 2.1.0 and Ruby 1.8.6

---

<div class="post-metadata">

**Author:** ![indigoi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@indigoi](https://www.ruby-forum.com/u/indigoi)\
**Post date:** [November 16, 2008, 12:36am UTC](https://www.ruby-forum.com/t/eager-loading-optimization/153375/2 "2008-11-16T00:36:27Z")

</div>

Richard S. wrote:

> and their associated children is killing my site load time (but not more  
> than eliminating the :include all together).
> 
> Is there a way to get only the first definition under an associated  
> phrase ( the definitions are ordered by rank) without having to write my  
> own SQL ??
> 
> Rails 2.1.0 and Ruby 1.8.6

Tricky, but investigate something like:

class Phrase \< ActiveRecord::Base  
has\_one :top\_ranked\_definition, :class\_name =\> ‘Definition’,  
:conditions =\> \<\<-END  
definitions.rank =  
(select max(rank) from definitions where phrase\_id = phrases.id)  
END

Phrase.find :all, :include =\> {:top\_ranked\_definition =\> :children},  
:conditions =\> ‘foo’

–  
Rails Wheels - Find Plugins, List & Sell Plugins -  
[http://railswheels.com](http://railswheels.com)
