# Eager load fail; why is this association loading individually?

**URL:** <https://www.ruby-forum.com/t/eager-load-fail-why-is-this-association-loading-individually/187739>\
**Category:** Rails\
**Created:** [April 28, 2010, 5:21pm UTC](https://www.ruby-forum.com/t/eager-load-fail-why-is-this-association-loading-individually/187739 "2010-04-28T17:21:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![brian](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/97f17d/32.png) [@brian](https://www.ruby-forum.com/u/brian)\
**Post date:** [April 28, 2010, 5:21pm UTC](https://www.ruby-forum.com/t/eager-load-fail-why-is-this-association-loading-individually/187739/1 "2010-04-28T17:21:54Z")

</div>

I’m trying to avoid the N+1 queries problem with eager loading, but  
it’s not working. The associated models are still being loaded  
individually.

Here are the relevant ActiveRecords and their relationships:

class Player \< ActiveRecord::Base  
has\_one :tableau  
end

Class Tableau \< ActiveRecord::Base  
belongs\_to :player  
has\_many :tableau\_cards  
has\_many :deck\_cards, :through =\> :tableau\_cards  
end

Class TableauCard \< ActiveRecord::Base  
belongs\_to :tableau  
belongs\_to :deck\_card, :include =\> :card  
end

class DeckCard \< ActiveRecord::Base  
belongs\_to :card  
has\_many :tableaus, :through =\> :tableau\_cards  
end

class Card \< ActiveRecord::Base  
has\_many :deck\_cards  
end

and the query I’m using is inside this method of Player:

def tableau\_contains(card\_id)  
self.tableau.tableau\_cards = TableauCard.find :all, :include =\>  
[{:deck\_card =\> (:card)}], :conditions =\> [‘tableau\_cards.tableau\_id  
= ?’, self.tableau.id]  
contains = false  
for tableau\_card in self.tableau.tableau\_cards  
# my logic here, looking at attributes of the Card model,  
with  
# tableau\_card.deck\_card.card  
# card is the model being loaded repeatedly and individually,  
after being loaded with the TableauCard.find :include  
end  
return contains  
end

Does it have to do with scope? This method is down a few calls in a  
larger loop in an observer, where I originally tried doing the eager  
loading because there are several places where these same objects are  
looped through and examined. In that observer, I load a @game object,  
and then load @game.players.

I eventually tried the code as it is above, with the load just before  
the loop, and I’m still seeing the individual SELECT queries for the  
individual cards objects inside the tableau\_cards loop in the log. I  
can see the eager-loading query with the IN clause just before the  
tableau\_cards loop as well.
