我正在尝试做这样的事情来预加载所有数据,所以每次循环运行时我都不必调用数据库。
# Get all data and do some eager loading
bets = Bet.find(:all, :include => :team_id)
games = Game.find(:all)
games.each do |game|
bets.find_all_by_user_id(user.id) # Now I want to get the specific bets, but I can't do find() on the returned array
end
和我尝试过的另一种方式
bets = Bet.where(:user_id => users) # users are an array of ID's
games = Game.find(:all)
games.each do |game|
bets.find_all_by_user_id(user.id) # This works, but it makes a db call every time, which makes the site really slow.
end
所以基本上我要做的是加载所有数据,然后在循环中使用它而无需联系数据库。最好的方法是什么?