alipman88
alipman88

Reputation: 33

Runoff-style voting using Rails/ActiveRecord

I'm working on a website for a "runoff election"-style contest, i.e. voters can vote for multiple candidates, but voters can only vote once for any individual candidate.

My models are:

Currently, I'm using the Cantor pairing function to create generate a unique integer/token for each vote, based on the candidate ID and voter ID. My vote model validates the uniqueness of this token, effectively preventing folks from voting more than once for a given candidate.

Even though my code works really well, I know there must be a way to use ActiveRecord associations and bypass the math, but I'm pretty new to Rails -- any input/discussion would be appreciated!

Upvotes: 0

Views: 72

Answers (1)

RobHeaton
RobHeaton

Reputation: 1390

Can you not just validate the uniqueness of the voter_id and candidate_id in the Vote table?

class Vote < ActiveRecord::Base

  validates_uniqueness_of :voter_id, scope: :candidate_id

end

You should add an index to the DB too:

add_index "votes", ["voter_id", "candidate_id"], unique: true

Upvotes: 1

Related Questions