Class: Decidim::DecidimAwesome::VoteWeight

Inherits:
ApplicationRecord show all
Defined in:
app/models/decidim/decidim_awesome/vote_weight.rb

Instance Method Summary collapse

Instance Method Details

#update_vote_weight_totals!Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'app/models/decidim/decidim_awesome/vote_weight.rb', line 14

def update_vote_weight_totals!
  extra = Decidim::DecidimAwesome::ProposalExtraField.find_or_initialize_by(proposal:)
  extra.vote_weight_totals = extra.vote_weight_totals || {}

  prev = weight_previous_change&.first
  if prev.present?
    extra.vote_weight_totals[prev.to_s] = Decidim::DecidimAwesome::VoteWeight.where(vote: proposal.votes, weight: prev).count
    extra.vote_weight_totals.delete(prev.to_s) if extra.vote_weight_totals[prev.to_s].zero?
  end
  extra.vote_weight_totals[weight.to_s] = Decidim::DecidimAwesome::VoteWeight.where(vote: proposal.votes, weight:).count
  extra.vote_weight_totals.delete(weight.to_s) if extra.vote_weight_totals[weight.to_s].zero?
  extra.weight_total = extra.vote_weight_totals.inject(0) { |sum, (weight, count)| sum + (weight.to_i * count) }
  extra.save!
end