poll_vote.rb 892 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: poll_votes
  5. #
  6. # id :bigint(8) not null, primary key
  7. # account_id :bigint(8)
  8. # poll_id :bigint(8)
  9. # choice :integer default(0), not null
  10. # created_at :datetime not null
  11. # updated_at :datetime not null
  12. # uri :string
  13. #
  14. class PollVote < ApplicationRecord
  15. belongs_to :account
  16. belongs_to :poll, inverse_of: :votes
  17. validates :choice, presence: true
  18. validates_with VoteValidator
  19. after_create_commit :increment_counter_cache
  20. delegate :local?, to: :account
  21. delegate :multiple?, :expired?, to: :poll, prefix: true
  22. def object_type
  23. :vote
  24. end
  25. private
  26. def increment_counter_cache
  27. poll.cached_tallies[choice] = (poll.cached_tallies[choice] || 0) + 1
  28. poll.save
  29. rescue ActiveRecord::StaleObjectError
  30. poll.reload
  31. retry
  32. end
  33. end