涉及多个表时,提高Rails视图生成速度

时间:2012-04-05 17:03:17

标签: ruby-on-rails activerecord

我有这些模型

class PlayersToTeam < ActiveRecord::Base
  belongs_to :player
  belongs_to :team

  accepts_nested_attributes_for :player
end

class Player < ActiveRecord::Base
  has_many :players_to_teams
  has_many :teams, through: :players_to_teams
end

class Team < ActiveRecord::Base
  has_many :players_to_teams
  has_many :players, through: :players_to_teams
  belongs_to :account
end

teams的展示视图中,我显示players上的所有team。编辑链接实际上是编辑players_to_teams条目,所以我有这样的东西:

  <% @team.players.each do |player| %>
  <tr>
    <td><%= player.FirstName %></td>
    <td><%= player.LastName %></td>
    <td><%= link_to "Edit", edit_players_to_team_path(player.players_to_teams.find_by_team_id(@team.id)) %></td>
  </tr>

其中@team被定义为Team.find(params[:id])。这是超慢的,当查看开发日志时,这是因为数据库被edit_players_to_team_path行的每个玩家多次击中(找到玩家,然后找到符合要求的player_to_team,或许更多?)。

所以我改为使用players_to team记录

<% @players_to_teams.each do |ptt| %>
  <tr>
    <td><%= ptt.player.FirstName %></td>
    <td><%= ptt.player.LastName %></td>
    <td><%= link_to "Edit", edit_players_to_team_path(ptt) %></td>
  </tr>
  <% end %>

其中@players_to_teams是控制器中team.players_to_teams的eqaul。这样做的速度要快得多,但我的视图中的每一行似乎都在点击数据库。

我猜测Team.find(params[:id])不会返回与players相关联的players_to_teamsteam条记录。有没有办法可以包含这些关联,以便调用Team.find(params[:id])返回一个引用playerplayer_to_teams相关记录的对象,这样db只会被命中一次? / p>

1 个答案:

答案 0 :(得分:0)

检索@player_to_teams记录时,请使用.include(:player)急切加载该查询中的玩家(实际语法可能因您使用的查询而异)。这样,应用程序将对数据库进行1次调用以获取ptt记录,并可能再调用一次以获取所有玩家。这将避免在视图中为每个ptt迭代查找播放器。这是一个演示 - http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

的链接