Module: Knitsearch::HasManyThroughJoinDependent

Extended by:
ActiveSupport::Concern
Defined in:
lib/knitsearch/has_many_through_join_dependent.rb

Instance Method Summary collapse

Instance Method Details

#knitsearch_refresh_through_parent_from_joinObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/knitsearch/has_many_through_join_dependent.rb', line 18

def knitsearch_refresh_through_parent_from_join
  dependents = Knitsearch.has_many_through_dependents[self.class]
  return unless dependents

  dependents.each do |dependent|
    parent_class = dependent[:parent_class]
    parent_fk = dependent[:parent_fk]
    parent_assoc = dependent[:parent_assoc]
    shadow_map = dependent[:columns]

    # Read the parent FK from the join row
    parent_id = read_attribute(parent_fk)
    next unless parent_id.present?

    # Find the parent and refresh its shadow columns
    parent = parent_class.find_by(id: parent_id)
    next unless parent

    # Recompute shadow columns for this parent
    updates = {}
    shadow_map.each do |shadow_col, source_col|
      values = parent.send(parent_assoc).pluck(source_col).compact.map(&:to_s)
      updates[shadow_col] = values.any? ? values.join(" ") : nil
    end

    parent.update_columns(updates)
  end
end