I’ve got these models
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
In my show view for teams, I show all the players on that team. The edit link actually goes to edit the players_to_teams entry, so I had something like this:
<% @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>
where @team was defined as Team.find(params[:id]). This was SUPER slow, and when looking at the dev logs, it was because the db was being hit numerous times for every player at the edit_players_to_team_path line (to find the player, then to find the player_to_team that matched the requirements, maybe more?).
So I switched it instead to use the players_to team record
<% @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 %>
where @players_to_teams is eqaul to team.players_to_teams in the controller. This goes a lot faster, but still seems to be hitting the db for every row in my view.
I’m guessing Team.find(params[:id]) doesn’t return the players or players_to_teams records that are associated with that team. Is there a way I can include those associations so that a call to Team.find(params[:id]) returns an object with references to both the player and player_to_teams associated records, so the db only gets hit once?
When retrieving the @player_to_teams records, eager load the players in that query using
.include(:player)(actual syntax may vary depending on the query you are using). That way the app will make 1 call to the database to get the ptt records and possibly one more call to get all the players. This will avoid having to lookup the player for each ptt iteration in the view. Here’s a link that demonstrates – http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations