Reputation: 542
I am using find_by_sql then ActiveRecord::Associations::Preloader to preload a few relations. I can see in the console that it is preloading the relations, yet for some reason it still lazy loads a portion of the associated records during the as_json call.
In this particular case, find_by_sql returned an array of 1872 models. Every model should have at least one associated details model. I used the below code to preload associations
preload = [
details: %i[account department]
]
ActiveRecord::Associations::Preloader.new.preload(results, preload)
To check if all the associations are preloaded, I used the below code
results.select{|r| r.association(:details).loaded? == false}.length
2
results.find_index{|r| r.association(:details).loaded? == false}
192
I wondered if for some reason the preloader would only preload a fixed number of records, but the index of the records that weren't loaded were't by each other or towards one end of the results array. They were at index 192 and 472.
Here is my as_json code
json = results.as_json(
include: [
details: {include: %i[department account]}
]
)
Is there some reason why it only preloads some of the relations. If I pass different search parameters to find_by_sql, it returns more models more preloaded relations, and more relations that aren't preloaded. If I use search parameters that return a small number of models, everything is preloaded.
Upvotes: 2
Views: 1156
Reputation: 542
I found out that the results array contained the same model twice because of a join condition in my SQL. Rails only preloaded associations for one of the duplicate models.
Upvotes: 1