Rails:在has_one关系上发生的额外数据库查询

时间:2016-12-30 17:17:30

标签: sql ruby-on-rails database associations

我正在构建一个rails应用程序,其中我有模型:Team,Player,Team_Player和许多属于Player的统计模型。 Team_Player模型充当中间连接团队和玩家。

我的问题是:当我打电话给

player = Player.find(team_player.player_id), 

rails进行了大量的数据库调用,不仅是Player模型,还有与Player相关的统计模型。我知道rails的默认行为不是加载相关的模型,除非我指定它。因此,我假设我已经在某处指定了这种行为。但是,老实说我不知道​​我在哪里/怎么做过。我意识到这是一个奇怪的问题,但鉴于以下内容,任何想法为什么要进行所有额外的数据库调用?

以下是我与模型相关的方法(使用示例统计模型):

class Team < ApplicationRecord
    has_many :team_players
end

class TeamPlayer < ApplicationRecord
    belongs_to :team
    belongs_to :player 
end


class Player < ApplicationRecord
    has_many :team_players
    has_one :passing_stats_season_total, dependent: :destroy

    delegate *PassingStatsSeasonTotal::ATTR_METHODS, to: :passing_stats_season_total

    after_initialize do
        self.build_passing_stats_season_total if passing_stats_season_total.nil?
    end 
end

class PassingStatsSeasonTotal < ApplicationRecord
    belongs_to :player

    ATTR_METHODS = [:attempts, :attempts=, etc.]
end

现在是我实际调用数据库的视图:

<tbody>
    <% @team.team_players.each do |team_player| %>
        <tr>
            <% player = Player.find(team_player.player_id) %>
            <td><%= player.name %></td>
            etc.
        </tr>
    <% end %>
</tbody>

这是控制台输出:

aPlayer = team.team_players.first
  TeamPlayer Load (0.3ms)  SELECT  "team_players".* FROM "team_players" WHERE "team_players"."team_id" = ? ORDER BY "team_players"."id" ASC LIMIT ?  [["team_id", 132], ["LIMIT", 1]]
 => #<TeamPlayer id: 1114, player_id: 8373, team_id: 132, created_at: "2016-12-30 00:11:42", updated_at: "2016-12-30 00:11:42"> 

player = Player.find(aPlayer.player_id)
  Player Load (0.1ms)  SELECT  "players".* FROM "players" WHERE "players"."id" = ? LIMIT ?  [["id", 8373], ["LIMIT", 1]]
  PassingStatsSeasonTotal Load (0.2ms)  SELECT  "passing_stats_season_totals".* FROM "passing_stats_season_totals" WHERE "passing_stats_season_totals"."player_id" = ? LIMIT ?  [["player_id", 8373], ["LIMIT", 1]]
 => #<Player id: # and a bunch of other stuff>

在这个例子中,为什么还加载了模型PassingStatsSeasonTotal? 我意识到这是一个奇怪的问题,但任何帮助都会非常感激。

谢谢!

2 个答案:

答案 0 :(得分:0)

我自己的回答:我删除了after_initialize块,并在我需要的时候在别处创建了统计模型。我不确定为什么after_initialize块改变了默认行为,但那是发生了什么。

答案 1 :(得分:0)

此行中的条件加载PassingStatsSeasonTotal关联:

self.build_passing_stats_season_total if passing_stats_season_total.nil?

原因是passing_stats_season_total是对关联的引用。在可以调用任何方法之前,Rails需要加载它。