X-Git-Url: https://projects.mako.cc/source/selectricity-live/blobdiff_plain/5a8b533b5abec8dc24674e4ef084b0b9779da8af..9abed97635edbac7fb1a687298fff5c5434cdff4:/app/models/vote.rb diff --git a/app/models/vote.rb b/app/models/vote.rb new file mode 100644 index 0000000..2aa1c4b --- /dev/null +++ b/app/models/vote.rb @@ -0,0 +1,38 @@ +class Vote < ActiveRecord::Base + belongs_to :voter + has_many :rankings + + def initialize + super + @votes = [] + end + + def votestring=(string="") + rel_votes = string.split("").collect { |vote| vote.to_i } + + # covert relative orders to absolute candidate ids + candidate_ids = voter.election.candidates.sort + candidate_ids.collect! { |candidate| candidate.id.to_i } + + rel_votes.collect! { |vote| candidate_ids[ vote - 1 ] } + @votes = rel_votes + end + + def save + rankings.each { destroy } unless rankings.empty? + @votes.each_with_index do |candidate, index| + ranking = Ranking.new + ranking.rank = index + 1 + ranking.candidate = Candidate.find(candidate) + self.rankings << ranking + end + + super + end + + def destroy + rankings.each { destroy } + super + end + +end