merged in support for full election results
[selectricity] / app / models / vote.rb
1 class Vote < ActiveRecord::Base
2   # relationships to other classes
3   belongs_to :voter
4   has_many :rankings
5   has_one :token
6   
7   # callbacks
8   after_update :save_rankings
9   before_destroy :destroy_rankings
10   
11   def to_s
12     votes.join("")
13   end
14
15   def each
16     self.votes.each {|vote| yield vote}
17   end
18
19   def votes
20     unless @votes
21       if rankings.empty?
22         @votes = Array.new
23       else
24         @votes = rankings.sort.collect { |ranking| ranking.candidate.id }
25       end
26     end
27
28     @votes
29   end
30
31   def votes=(array)
32     @votes = array
33   end
34
35   def save_rankings
36     destroy_rankings
37     self.votes.each_with_index do |candidate_id, index| 
38       ranking = Ranking.new
39       ranking.rank = index
40       ranking.candidate =  Candidate.find(candidate_id)
41       self.rankings << ranking
42     end
43   end
44   
45   def destroy
46     self.destroy_rankings
47     super
48   end
49
50   def destroy_rankings 
51     rankings.each { |ranking| ranking.destroy }
52   end
53
54   def settime
55     self.time = Time.now
56     self.save
57   end
58
59   def confirm!
60     self.confirmed = 1
61     self.save
62     
63     unless self.voter.election.quickvote?
64       token.destroy and token.reload if token
65       self.token = Token.new
66       self.save
67     end
68   end
69
70   def confirm?
71     confirmed == 1
72   end
73   
74   def votestring
75     # create a mapping of candidates ids and the relative order of the
76     # candidates as they appear when sorted alphabetically
77     cand_relnums = {}
78     self.voter.election.candidates.sort.each_with_index do |c, i|
79       cand_relnums[c.id] = i + 1
80     end
81
82     # assemble the votestring
83     self.votes.collect {|v| (cand_relnums[v] + 64).chr}.join("")
84   end
85
86   # the following subroutine is used for quickvotes, but need for elections now
87   # too. It creates a vote with the candidates listed in order of preference 
88   # based on alphabetical order. Meant to be manipulated and then confirmed
89   def set_defaults!  
90     self.votes = voter.election.candidates.sort.collect {|c| c.id }
91     self.save
92   end
93          
94 end

Benjamin Mako Hill || Want to submit a patch?