Module: ActiveRecord::AssociationPreload::ClassMethods

Defined in:
lib/acts_as_joinable/active_record_patch.rb

Instance Method Summary collapse

Instance Method Details

#find_associated_records(ids, reflection, preload_options) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/acts_as_joinable/active_record_patch.rb', line 4

def find_associated_records(ids, reflection, preload_options)
  options = reflection.options
  table_name = reflection.klass.quoted_table_name

  if interface = reflection.options[:as]
    conditions = "#{reflection.klass.quoted_table_name}.#{connection.quote_column_name "#{interface}_id"} #{in_or_equals_for_ids(ids)} and #{reflection.klass.quoted_table_name}.#{connection.quote_column_name "#{interface}_type"} IN ('#{self.name}','#{self.base_class.sti_name}')"
  else
    foreign_key = reflection.primary_key_name
    conditions = "#{reflection.klass.quoted_table_name}.#{foreign_key} #{in_or_equals_for_ids(ids)}"
  end

  conditions << append_conditions(reflection, preload_options)

  reflection.klass.with_exclusive_scope do
    reflection.klass.find(:all,
                        :select => (preload_options[:select] || options[:select] || "#{table_name}.*"),
                        :include => preload_options[:include] || options[:include],
                        :conditions => [conditions, ids],
                        :joins => options[:joins],
                        :group => preload_options[:group] || options[:group],
                        :order => preload_options[:order] || options[:order])
  end
end

#preload_through_records(records, reflection, through_association) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/acts_as_joinable/active_record_patch.rb', line 28

def preload_through_records(records, reflection, through_association)
  through_reflection = reflections[through_association]
  through_primary_key = through_reflection.primary_key_name

  if reflection.options[:source_type]
    interface = reflection.source_reflection.options[:foreign_type]
    preload_options = {:conditions => ["#{connection.quote_column_name interface} IN (?)", reflection.options[:source_type]]}
    
    records.compact!
    records.first.class.preload_associations(records, through_association, preload_options)

    # Dont cache the association - we would only be caching a subset
    through_records = []
    records.each do |record|
      proxy = record.send(through_association)

      if proxy.respond_to?(:target)
        through_records << proxy.target
        proxy.reset
      else # this is a has_one :through reflection
        through_records << proxy if proxy
      end
    end
    through_records.flatten!
  else
    records.first.class.preload_associations(records, through_association)
    through_records = records.map {|record| record.send(through_association)}.flatten
  end
  through_records.compact!
  through_records
end