我有这些模型
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
控制器中 eqaul 的位置在哪里team.players_to_teams
。这速度要快得多,但在我看来,每一行似乎仍然在击中数据库。
我猜Team.find(params[:id])
不会返回与that 相关联的players
or记录。有没有一种方法可以包含这些关联,以便调用返回一个对象,该对象同时引用和关联记录,因此数据库只被命中一次?players_to_teams
team
Team.find(params[:id])
player
player_to_teams