Class: ActiveRecord::Associations::CountPreloader::Count
- Inherits:
-
Preloader::HasOne
- Object
- Preloader::HasOne
- ActiveRecord::Associations::CountPreloader::Count
show all
- Defined in:
- lib/includes-count.rb
Instance Method Summary
collapse
Constructor Details
#initialize(klass, owners, reflection, preload_options) ⇒ Count
Returns a new instance of Count.
11
12
13
14
|
# File 'lib/includes-count.rb', line 11
def initialize(klass, owners, reflection, preload_options)
super
@preload_options[:select] ||= "#{table.name}.#{association_key_name}, COUNT(id) AS #{count_name}"
end
|
Instance Method Details
#build_scope ⇒ Object
32
33
34
|
# File 'lib/includes-count.rb', line 32
def build_scope
super.group(association_key)
end
|
#count_name ⇒ Object
16
17
18
|
# File 'lib/includes-count.rb', line 16
def count_name
preload_options[:count_name].try(:to_s) || "#{reflection.name}_count"
end
|
#preload ⇒ Object
20
21
22
23
24
25
26
27
28
29
30
|
# File 'lib/includes-count.rb', line 20
def preload
associated_records_by_owner.each do |owner, associated_records|
sum = associated_records.map{|r| r[count_name] || 0}.sum
owner.instance_eval "
def #{count_name}
@#{count_name} ||= 0
@#{count_name} += #{sum}
end
"
end
end
|