Вопрос

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:

  • candidate

  • voter

  • vote

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!

Это было полезно?

Решение

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top