How can I get rid of the n + 1 query related to rails association?

I have a line in my code as shown below ...

injury.player_extract.player

      

I get a notification from the named gem, bullet, that a request n + 1 has been detected. Now there is an association from injury to player extraction and then player_extract for the player, which I will discuss below. I tried to add -> { includes: player}

like what the bullet recommended, but I still get the error. Can someone explain why I am still getting it?

Associations

injury.rb

belongs_to :player_extract, -> { includes :player },  class_name: 'PlayerExtract', foreign_key: 'Playerid', primary_key: 'Playerid'

      

player_extract.rb

belongs_to :player, foreign_key: 'Playerid', primary_key: 'leagueid'

      

player.rb

has_one :player_extract, class_name: 'PlayerExtract', foreign_key: 'Playerid', primary_key: 'leagueid'

      

+3


source to share


1 answer


You should probably use eager loading of all data to fix the problem.

From a short inspection, it appears that you are using the directive includes

on injury.rb

, but not on player_extract.rb

- so that it is Player

lazy loaded whenever PlayerExtract

used to access the actual data.

Take a look at these links:



I would probably consider using the highlighted area with joins

( here ) or a directive includes

... I'm not sure if directives in relationship declarations ( has_one

etc.) are the best way to do this.

0


source







All Articles