4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
# File 'lib/cached_at/associations/has_many_through_association.rb', line 4
def touch_cached_at(timestamp, method)
using_reflection = reflection.parent_reflection || reflection
if using_reflection.options[:cached_at]
return if method == :create && !using_reflection.is_a?(ActiveRecord::Reflection::HasAndBelongsToManyReflection)
if using_reflection.inverse_of.nil?
puts "WARNING: cannot updated cached at for relationship: #{owner.class.name}.#{using_reflection.name}, inverse_of not set"
return
end
cache_column = "#{using_reflection.inverse_of.name}_cached_at"
query = nil
if loaded?
target.each { |r| r.send(:write_attribute_without_type_cast, cache_column, timestamp) }
query = klass.where(klass.primary_key => target.map(&:id))
else
ids = [owner.send(using_reflection.association_primary_key), owner.send("#{using_reflection.association_primary_key}_before_last_save")].compact.uniq
arel_table = klass._reflections[using_reflection.inverse_of.options[:through].to_s].klass.arel_table
query = klass.joins(using_reflection.inverse_of.options[:through])
query = if using_reflection.is_a?(ActiveRecord::Reflection::HasAndBelongsToManyReflection)
query.where(arel_table[using_reflection.foreign_key].in(ids))
else
query.where(arel_table[using_reflection.inverse_of.foreign_key].in(ids))
end
end
query.update_all({ cache_column => timestamp })
traverse_relationships(klass, options[:cached_at], query, cache_column, timestamp)
end
if !owner.new_record? && using_reflection.inverse_of && using_reflection.inverse_of.options[:cached_at]
cache_column = "#{using_reflection.name}_cached_at"
owner.send(:write_attribute_without_type_cast, cache_column, timestamp)
owner.update_columns(cache_column => timestamp)
end
end
|