我试图避免急切加载的 N+1 查询问题,但它不起作用。相关模型仍在单独加载。
以下是相关的 ActiveRecords 及其关系:
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
class Turn < ActiveRecord::Base
belongs_to :game
end
我正在使用的查询在 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;
# individual loads of related Card models related to tableau_card are done here
end
return contains
end
它与范围有关吗?这个 tableau_contains 方法在一个更大的循环中减少了几个方法调用,我最初尝试进行急切加载,因为有几个地方循环和检查这些相同的对象。然后我最终尝试了上面的代码,在循环之前加载,我仍然在日志中的 tableau_cards 循环中看到 Card 的单个 SELECT 查询。我也可以在 tableau_cards 循环之前看到带有 IN 子句的急切加载查询。
编辑:下面有更大的外循环的附加信息
EDIT2:用答案中的提示纠正了下面的循环
EDIT3:在目标循环中添加了更多细节
这是更大的循环。它在 after_save 的观察者内
def after_save(pa)
turn = Turn.find(pa.turn_id, :include => :player_actions)
game = Game.find(turn.game_id, :include => :goals)
game.players.all(:include => [ :player_goals, {:tableau => [:tableau_cards => [:deck_card => [:card]]]} ])
if turn.phase_complete(pa, players) # calls player.tableau_contains(card)
for goal in game.goals
if goal.checks_on_this_phase(pa)
if goal.is_available(players, pa, turn)
for player in game.players
goal.check_if_player_takes(player, turn, pa)
... # loop through player.tableau_cards
end
end
end
end
end
end
这是turn类中的相关代码:
def phase_complete(phase, players)
all_players_complete = true
for player in players
if(!player_completed_phase(player, phase))
all_players_complete = false
end
end
return all_players_complete
end
正在for player in game.players
执行另一个查询以加载播放器。它被缓存了,我的意思是它在日志中有 CACHE 标签,但我认为根本不会有任何查询,因为 game.players 应该已经加载到内存中。
目标模型的另一个片段:
class Goal < ActiveRecord::Base
has_many :game_goals
has_many :games, :through => :game_goals
has_many :player_goals
has_many :players, :through => :player_goals
def check_if_player_takes(player, turn, phase)
...
for tab_card in player.tableau_cards
...
end
end