Brian
2010-Apr-28 15:20 UTC
eager load fail; why is this association loading individually?
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. -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.