Rails ActiveRecord helper lookup method does not support loading

I have the following models: Game and Pick. There is one and every connection between the Games and the Peak. There is a third model called "Player", the player has a lot of choices.

There is a method in the Player class that finds a choice for a given game or creates a new one if it does not exist.

class Player < ActiveRecord::Base has_many :picks def pick_for_game(game) game_id = game.instance_of?(Game) ? game.id : game picks.find_or_initialize_by_game_id(game_id) end end 

I want to download games with pleasure for every choice. However, if I do

 picks.find_or_initialize_by_game_id(game_id, :include => :game) 

First, he selects selections when this query is run (the method is run several times), and then he selects games as he accesses each element. If I add default_scope to the Pick class

 class Pick < ActiveRecord::Base belongs_to :game belongs_to :player default_scope :include => :game end 

It still generates 2 selection statements for each selection, but now it loads the game right after the selection, but it still doesn't make the connection, as I expect.

 Pick Load (0.2ms) SELECT "picks".* FROM "picks" WHERE "picks"."game_id" = 1 AND ("picks".player_id = 1) LIMIT 1 Game Load (0.4ms) SELECT "games".* FROM "games" WHERE ("games"."id" = 1) 
+4
source share
2 answers

First, find does not support the include or join parameter as a parameter. (As mipsy said, it doesn't make sense for find to support include , as this will be the same number of requests as loading later).

Secondly, include impatiently loads the association, so something like

 Person.includes(:company) 

roughly equivalent to doing:

 Person.all.each { |person| Company.find(person.company_id) 

I say roughly equivalent, because the former has O(1) (really two) queries, while the latter are O(n) queries, where n is the number of people.

The connection, however, will be just one request, but the disadvantage of the connection is that you cannot always use the extracted data to update the model. To make a connection, you must:

 Person.join(:companies) 

For more information, see the Rails manual .

To summarize, a join does not load because it does not load the association, and simultaneously loads both pieces of data. I understand that there is a strange fine line between them, but we look forward to loading other data proactively, but you won’t receive this data later through the connection, or you would have already received it in your original request! Hope this makes sense.

+2
source

I think that was how it should have worked. Desired loading is primarily used to make iterations over large collections of models more efficient, selecting them all at once - it will not matter if you are simply dealing with a single object.

+1
source

Source: https://habr.com/ru/post/1346327/


All Articles