forked from ManageIQ/manageiq
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add support for scopes to MiqPreloader#preload
We want to use preloaded data to populate a record's associations Rails currently accepts a scope for preloading, but it runs the scope for every input record We are using this to load VimPerformanceState values for a single record We also want the list of records after it is done. Before ====== ```ruby ems = ExtManagementSystem.take(5).to_a vms = Vm.where(:ems => ems.map(&:id)).load MiqPreloader.preload(ems, :vms, vms) # => 5 queries MiqPreloader.preload(ems, :vms, vms.to_a) # error ``` After ===== ```ruby ems = ExtManagementSystem.take(5).to_a vms = Vm.where(:ems => ems.map(&:id)).load MiqPreloader.preload(ems, :vms, vms) # => 5 queries MiqPreloader.preload(ems, :vms, vms.to_a) # error ```
- Loading branch information
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
module ActiveRecordPreloadScopes | ||
# based upon active record 6.1 | ||
def records_for(ids) | ||
# use our logic if passing in [ActiveRecord::Base] or passing in a loaded Relation/scope | ||
unless (preload_scope.kind_of?(Array) && preload_scope.first.kind_of?(ActiveRecord::Base)) || | ||
preload_scope.try(:loaded?) | ||
return super | ||
end | ||
|
||
preload_scope.each do |record| | ||
owner = owners_by_key[convert_key(record[association_key_name])].first | ||
association = owner.association(reflection.name) | ||
association.set_inverse_instance(record) | ||
end | ||
end | ||
end | ||
|
||
ActiveRecord::Associations::Preloader::Association.prepend(ActiveRecordPreloadScopes) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters