docbrown/app/models/poll_vote.rb
Jeremy Friesen b115b2d17e
Appeasing Rubocop as it sneaks some changes in (#16085)
I was working on another branch and as part of my commit, Rubocop
removed a validation (but not the spec that asserted the validation).

Below is the "non-updating" rubocop offense on the other branch.

```shell
❯ rubocop ./app/models/notification_subscription.rb
Inspecting 1 file
C

Offenses:

app/models/notification_subscription.rb:13:29: C: [Correctable]
Rails/RedundantPresenceValidationOnBelongsTo: Remove explicit presence
validation for notifiable_id.
  validates :notifiable_id, presence: true
                            ^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense auto-correctable
```

To remediate, I ran:

```shell
> rubocop --only "Rails/RedundantPresenceValidationOnBelongsTo" \
  --auto-correct
```

This resolved the `app/models`.  Then did some regex magic and removed
the assertions from `spec/models`.

For Forem folks, I wrote a [forem.team post][1] discuss if this is how
we want to proceed.

[1]:https://forem.team/jeremy/rubocop-auto-updating-mayhem-33a6
2022-01-13 07:48:01 -05:00

40 lines
1.3 KiB
Ruby

# @note When we destroy the related user, it's using dependent:
# :delete for the relationship. That means no before/after
# destroy callbacks will be called on this object.
#
# @note When we destroy the related poll, it's using dependent:
# :delete for the relationship. That means no before/after
# destroy callbacks will be called on this object.
class PollVote < ApplicationRecord
belongs_to :user
belongs_to :poll_option
belongs_to :poll
counter_culture :poll_option
counter_culture :poll
# In the future we'll remove this constraint if/when we allow multi-answer polls
validates :poll_id, uniqueness: { scope: :user_id }
validates :poll_option_id, uniqueness: { scope: :user_id }
validate :one_vote_per_poll_per_user
after_destroy :touch_poll_votes_count
after_save :touch_poll_votes_count
delegate :poll, to: :poll_option, allow_nil: true
private
def one_vote_per_poll_per_user
return false unless poll
return false unless poll.vote_previously_recorded_for?(user_id: user_id)
errors.add(:base, "cannot vote more than once in one poll")
end
def touch_poll_votes_count
poll.update_column(:poll_votes_count, poll.poll_votes.size)
poll_option.update_column(:poll_votes_count, poll_option.poll_votes.size)
end
end