3

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

injury.player_extract.player

I'm getting a notification from a gem called, bullet that there is an n+1 query detected. Now there is an association from injury to player extract, and then player_extract to player -- which I'll outline below. I've tried adding -> { includes: player} as that's what bullet recommended but I still receive the error. Can anyone explain why I would still be receiving 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'
daveomcd
  • 6,367
  • 14
  • 83
  • 137
  • Why on earth are you using the column name `Playerid`? Unless you have to share the database with some other legacy app you should rename it to `player_id` – max Aug 02 '15 at 21:22
  • you got it right with legacy app, i have no control over the names -- although I just though... could I use `alias_attribute` to get the functionality of player_id ? Perhaps I should have a separate question if it's more in depth than yes/no – daveomcd Aug 02 '15 at 21:23
  • What is the role of PlayerExtract model? – max Aug 02 '15 at 21:27
  • PlayerExtract is similar to Player except they're in two different databases and have slightly different attributes, but share alot of common ones. So I'm just accessing the player model to access an id field on it -- It's not ideal but as I said I don't have control over the data. – daveomcd Aug 02 '15 at 21:31
  • could you add your schema.rb or an extract of the relevant parts? You might want to declare a `has_one :player, through: :player_extract` relation on injury - but I would like to test the answer out since its a pretty unconventional case. – max Aug 02 '15 at 21:47

1 Answers1

0

You should probably use eager loading on all the data to resolve the issue.

From a short inspection it seems that you are using the includes directive on injury.rb but not on player_extract.rb - so that the Player is lazily loaded whenever the PlayerExtract is used to access the actual data.

Have a look at these links:

I would probably consider using a dedicated scope with the joins (here) or includes directives... I'm not sure putting the directives in the relations declarations (has_one etc') is the best way to go about it.

Community
  • 1
  • 1
Myst
  • 18,516
  • 2
  • 45
  • 67