poll_vote.rb 833 B

123456789101112131415161718192021222324252627282930313233343536373839
  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. def object_type
  22. :vote
  23. end
  24. private
  25. def increment_counter_cache
  26. poll.cached_tallies[choice] = (poll.cached_tallies[choice] || 0) + 1
  27. poll.save
  28. rescue ActiveRecord::StaleObjectError
  29. poll.reload
  30. retry
  31. end
  32. end