To get the heading where a user voted, we were relying on the `balloted_heading_id` field. Our guess is this was done so the total number of users is the same as the sum of users who voted on a heading. That is, if 2000 people voted just on the "All city" heading, 1000 voted just on the "North district" heading, and 500 people voted on both, instead of showing "3500 people voted in total, 2500 voted in all city, 1500 voted in north district", we show something like "3500 people voted in total, 2250 voted in all city, and 1250 voted in north district". However, this approach has some disadvantages. The first disadvantage is, the stats aren't correct. In the case above, 2500 voted on the "All city heading", so the statistics for this heading don't show reality. The second one is we weren't considering the last heading where users voted inside the budget being displayed, but the last heading where users voted, period. That means that, if all the people above voted on a later budget, the stats for the budget above would become "3500 people voted in total, 0 voted in all city, and 0 voted in north district". That also means we were including headings from previous budgets in the statistics for more recent budgets when people hadn't voted on the recent ones. So we're removing the `balloted_heading_id` since its data is lost once people vote on a new budget. And, in order to show the right stats and simplify the code, we're no longer trying to add votes just to one heading when users vote on several headings. Co-Authored-By: Julian Nicolas Herrero <microweb10@gmail.com>
48 lines
1.3 KiB
Ruby
48 lines
1.3 KiB
Ruby
class Budget
|
|
class Ballot
|
|
class Line < ApplicationRecord
|
|
belongs_to :ballot, counter_cache: :ballot_lines_count
|
|
belongs_to :investment, counter_cache: :ballot_lines_count
|
|
belongs_to :heading
|
|
belongs_to :group
|
|
belongs_to :budget
|
|
|
|
validates :ballot_id, :investment_id, :heading_id, :group_id, :budget_id, presence: true
|
|
|
|
validate :check_selected
|
|
validate :check_enough_resources
|
|
validate :check_valid_heading
|
|
|
|
scope :by_investment, ->(investment_id) { where(investment_id: investment_id) }
|
|
|
|
before_validation :set_denormalized_ids
|
|
|
|
def check_enough_resources
|
|
ballot.lock!
|
|
|
|
unless ballot.enough_resources?(investment)
|
|
errors.add(:resources, ballot.not_enough_resources_error)
|
|
end
|
|
end
|
|
|
|
def check_valid_heading
|
|
return if ballot.valid_heading?(heading)
|
|
|
|
errors.add(:heading, "This heading's budget is invalid, or a heading on the same group was already selected")
|
|
end
|
|
|
|
def check_selected
|
|
errors.add(:investment, "unselected investment") unless investment.selected?
|
|
end
|
|
|
|
private
|
|
|
|
def set_denormalized_ids
|
|
self.heading_id ||= investment&.heading_id
|
|
self.group_id ||= investment&.group_id
|
|
self.budget_id ||= investment&.budget_id
|
|
end
|
|
end
|
|
end
|
|
end
|