Variety of improvements and additions:
[selectricity] / app / models / vote.rb
1 class Vote < ActiveRecord::Base
2   belongs_to :voter
3   has_many :rankings
4   
5   def initialize
6     super
7     @votes = []
8   end
9   
10   def votestring=(string="")
11     rel_votes = string.split("").collect { |vote| vote.to_i }
12     
13     # covert relative orders to absolute candidate ids
14     candidate_ids = voter.election.candidates.sort
15     candidate_ids.collect! { |candidate| candidate.id.to_i }
16    
17     rel_votes.collect! { |vote| candidate_ids[ vote - 1 ] }
18     @votes = rel_votes
19   end
20
21   def save 
22     rankings.each { destroy } unless rankings.empty?
23     @votes.each_with_index do |candidate, index| 
24       ranking = Ranking.new
25       ranking.rank = index + 1
26       ranking.candidate =  Candidate.find(candidate)
27       self.rankings << ranking
28     end
29       
30     super
31   end
32
33   def destroy
34     rankings.each { destroy }
35     super
36   end
37
38 end

Benjamin Mako Hill || Want to submit a patch?