Ruby on rails 在RubyonRails中从数据库预加载数据

Ruby on rails 在RubyonRails中从数据库预加载数据,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在尝试这样做来预加载所有数据,这样我就不必每次循环运行时都调用数据库 # 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

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

# 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

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

您可能需要在之前的某个点进行调用,将数据保存在变量中,然后在循环中访问该变量。大概是这样的:

games = Game.all

bets = Bet.all

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

不要在数组中使用finder方法:如果使用,将再次查询数据库。坚持对已有的数据采取行动。

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

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

user.games.all( :include => :bets ).each do |game|
  game.bets # will be already loaded
end
在这里:
:include-应同时加载的名称关联。命名的符号表示已定义的关联。-引用。

在给出任何建议之前,您必须提供有关应用程序体系结构的更多信息。是网络吗?可移动的windows窗体?DAL是如何通过web服务设计的?