From f9fb76ec976733aace1dbb121b080caad1d0ca98 Mon Sep 17 00:00:00 2001 From: rhymes Date: Mon, 17 Jun 2019 16:28:05 +0200 Subject: [PATCH] Remove double presence validator in PollVote (#3187) [ci skip] --- app/models/poll_vote.rb | 12 +++++++----- spec/models/poll_vote_spec.rb | 4 ++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/app/models/poll_vote.rb b/app/models/poll_vote.rb index b9f3110d1..dcc5b4e13 100644 --- a/app/models/poll_vote.rb +++ b/app/models/poll_vote.rb @@ -6,21 +6,23 @@ class PollVote < ApplicationRecord counter_culture :poll_option counter_culture :poll - validates :poll_id, presence: true, presence: true, uniqueness: { scope: :user_id } # In the future we'll remove this constraint if/when we allow multi-answer polls + validates :poll_id, presence: true, uniqueness: { scope: :user_id } # In the future we'll remove this constraint if/when we allow multi-answer polls validates :poll_option_id, presence: true, uniqueness: { scope: :user_id } validate :one_vote_per_poll_per_user after_save :touch_poll_votes_count after_destroy :touch_poll_votes_count - def poll - poll_option.poll - end + delegate :poll, to: :poll_option, allow_nil: true private def one_vote_per_poll_per_user - errors.add(:base, "cannot vote more than once in one poll") if poll.poll_votes.where(user_id: user_id).any? || poll.poll_skips.where(user_id: user_id).any? + return false unless poll + + has_votes = ( + poll.poll_votes.where(user_id: user_id).any? || poll.poll_skips.where(user_id: user_id).any?) + errors.add(:base, "cannot vote more than once in one poll") if has_votes end def touch_poll_votes_count diff --git a/spec/models/poll_vote_spec.rb b/spec/models/poll_vote_spec.rb index d4d796206..9862279be 100644 --- a/spec/models/poll_vote_spec.rb +++ b/spec/models/poll_vote_spec.rb @@ -5,6 +5,10 @@ RSpec.describe PollVote, type: :model do let(:user) { create(:user) } let(:poll) { create(:poll, article_id: article.id) } + it "is not valid as a new object" do + expect(PollVote.new.valid?).to be(false) + end + it "limits one vote per user per poll" do create(:poll_vote, poll_option_id: poll.poll_options.last.id, user_id: user.id, poll_id: poll.id) PollVote.create(poll_option_id: poll.poll_options.first.id, user_id: user.id, poll_id: poll.id)