I’m trying to do something like this to preload all data, so I don’t have to a database call every time the loop runs.
# 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
and the other way I’ve tried
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
So basically what I’m trying to do is to load all data, and then use it in the loop without having to contact the database. What is the best approach to this?
You’ll probably have to make the call at some previous point, save the data in a variable, and then access that variable in the loop. Something like this:
Don’t use finder methods inside the array: if you do, you’ll query the database again. Stick with the Ruby enumerable methods to act on the data you already have.