# Find and include problem

**URL:** <https://www.ruby-forum.com/t/find-and-include-problem/184311>\
**Category:** Rails\
**Created:** [February 28, 2010, 6:25pm UTC](https://www.ruby-forum.com/t/find-and-include-problem/184311 "2010-02-28T18:25:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![LeonS](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/c77e96/32.png) [@LeonS](https://www.ruby-forum.com/u/LeonS)\
**Post date:** [February 28, 2010, 6:25pm UTC](https://www.ruby-forum.com/t/find-and-include-problem/184311/1 "2010-02-28T18:25:51Z")

</div>

Hi,

I’m trying to reduce my queries to the database so i use includes, but  
there is produced a query every time and i can’t see an improvement.  
What does i’m doing wrong?

In controller:

@matches = @stage.matches.find(:all,:include =\>  
[:team\_1,:team\_2, :match\_tips])

In view:

\<% @matches.each do |match| %\>  
\<% if @tipped\_matches.include? match %\>  
\<% tip = match.match\_tips.find\_by\_user\_id(current\_user.id) %\>  
…

So the third line will produce every turn through the loop a query,  
thats not good, how can i avoid that?

---

<div class="post-metadata">

**Author:** ![LeonS](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/c77e96/32.png) [@LeonS](https://www.ruby-forum.com/u/LeonS)\
**Post date:** [February 28, 2010, 6:45pm UTC](https://www.ruby-forum.com/t/find-and-include-problem/184311/2 "2010-02-28T18:45:10Z")

</div>

On Feb 28, 5:24 pm, LeonS [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Hi,
> 
> I’m trying to reduce my queries to the database so i use includes, but  
> there is produced a query every time and i can’t see an improvement.  
> What does i’m doing wrong?

It’s because you’re calling find\_by\_xxx which will always cause a  
query.  
you could instead do match.match\_tips.detect {|m| m.user\_id ==  
current\_user.id}

Fred
