+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