1

我正在尝试做这样的事情来预加载所有数据,所以每次循环运行时我都不必调用数据库。

# 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

所以基本上我要做的是加载所有数据,然后在循环中使用它而无需联系数据库。最好的方法是什么?

4

2 回答 2

2

您可能必须在之前的某个时间点进行调用,将数据保存在变量中,然后在循环中访问该变量。像这样的东西:

games = Game.all

bets = Bet.all

games.each do |game|
    bets.select {|b| b.user_id == user.id}
end

不要在数组中使用查找器方法:如果这样做,您将再次查询数据库。坚持使用Ruby 可枚举方法来处理您已有的数据。

于 2012-05-17T15:30:32.347 回答
1

我不确定您要做什么...您从哪里获得用户变量。为什么你需要在每场比赛中显示所有投注?所以,我希望您的投注属于用户并发布到某个游戏。并且您需要列出用户参与的每场比赛的所有投注?因此,在用户中应该是:

has_many :bets    
has_many :games, :through => :bets

现在:

user.games.all( :include => :bets ).each do |game|
  game.bets # will be already loaded
end

此处: :include - 命名应该一起加载的关联。命名的符号是指已定义的关联。- 从Rails API引用。

于 2012-05-17T15:58:18.510 回答