# A backwards N+1 problem

**URL:** <https://www.ruby-forum.com/t/a-backwards-n-1-problem/151906>\
**Category:** Ruby\
**Created:** [October 27, 2008, 6:48pm UTC](https://www.ruby-forum.com/t/a-backwards-n-1-problem/151906 "2008-10-27T18:48:16Z")\
**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:** [October 27, 2008, 6:48pm UTC](https://www.ruby-forum.com/t/a-backwards-n-1-problem/151906/1 "2008-10-27T18:48:16Z")

</div>

Hey, iâ€™m running into an N+1 problem, but i don’t exactly know how to  
:include in this situation. (controller code is at the bottom).

I’m trying to find all of the highest ranked definitions, and then  
render their associated phrases.

A Phrase has many definitions. A Definition has many children

I already have all the info i need stored in @definitions, so this  
should only require one SQL call, but unfortunately this line:

@Phrases \<\< definition.phrase(:include =\> [:definitions =\> :children])

Doesnâ€™t actually work.

Below is my controller code. Rails 2.1.0, Ruby 1.8.6â€¦Thanks ahead of  
time

def index  
@definitions = Definition.find(:all, :include =\> [:children,  
:phrase], :limit =\> 10, :order =\> ‘rank DESC’)  
@Phrases = []  
for definition in @definitions  
@Phrases \<\< definition.phrase(:include =\> [:definitions =\>  
:children])  
end  
@Phrases = @Phrases.uniq  
if @Phrases != nil  
@new\_phrases = @Phrases.paginate(:page =\> params[:page], :order  
=\> ‘word ASC’, :per\_page =\> 5)  
end ## if @phrase !=nil  
end ##def index

The full capture can be found under my [Five Runs Account](https://tuneup.fiveruns.com/runs/699)

If you have any suggestions i would love for my main page to not take  
5000 milliseconds to load : )

---

<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:** [October 27, 2008, 10:57pm UTC](https://www.ruby-forum.com/t/a-backwards-n-1-problem/151906/2 "2008-10-27T22:57:18Z")

</div>

Richard S. wrote:

> Hey, iâ€™m running into an N+1 problem, but i don’t exactly know how to  
> :include in this situation. (controller code is at the bottom).

Try asking on the Ruby on Rails list: [http://www.ruby-forum.com/forum/3](http://www.ruby-forum.com/forum/3)
