method
preload_belongs_to_association
Ruby on Rails latest stable (v7.1.3.2)
-
0 notes -
Class: ActiveRecord::AssociationPreload::ClassMethods
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0 (0)
- 2.2.1 (-38)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (0)
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
preload_belongs_to_association(records, reflection, preload_options={})
private
Hide source
# File activerecord/lib/active_record/association_preload.rb, line 304 def preload_belongs_to_association(records, reflection, preload_options={}) return if records.first.send("loaded_#{reflection.name}?") options = reflection.options primary_key_name = reflection.primary_key_name if options[:polymorphic] polymorph_type = options[:foreign_type] klasses_and_ids = {} # Construct a mapping from klass to a list of ids to load and a mapping of those ids back # to their parent_records records.each do |record| if klass = record.send(polymorph_type) klass_id = record.send(primary_key_name) if klass_id id_map = klasses_and_ids[klass] ||= {} id_list_for_klass_id = (id_map[klass_id.to_s] ||= []) id_list_for_klass_id << record end end end klasses_and_ids = klasses_and_ids.to_a else id_map = {} records.each do |record| key = record.send(primary_key_name) if key mapped_records = (id_map[key.to_s] ||= []) mapped_records << record end end klasses_and_ids = [[reflection.klass.name, id_map]] end klasses_and_ids.each do |klass_and_id| klass_name, id_map = *klass_and_id next if id_map.empty? klass = klass_name.constantize table_name = klass.quoted_table_name primary_key = (reflection.options[:primary_key] || klass.primary_key).to_s column_type = klass.columns.detect{|c| c.name == primary_key}.type ids = id_map.keys.map do |id| if column_type == :integer id.to_i elsif column_type == :float id.to_f else id end end conditions = "#{table_name}.#{connection.quote_column_name(primary_key)} #{in_or_equals_for_ids(ids)}" conditions << append_conditions(reflection, preload_options) associated_records = klass.unscoped.where([conditions, ids]).apply_finder_options(options.slice(:include, :select, :joins, :order)).to_a set_association_single_records(id_map, reflection.name, associated_records, primary_key) end end