# frozen_string_literal: true # == Schema Information # # Table name: poll_votes # # id :integer not null, primary key # rank :integer # created_at :datetime not null # poll_option_id :integer not null # user_id :integer not null # # Indexes # # index_poll_votes_on_poll_option_id_and_user_id (poll_option_id,user_id) UNIQUE # index_poll_votes_on_user_id (user_id) # # Foreign Keys # # fk_rails_... (poll_option_id => poll_options.id) ON DELETE => cascade ON UPDATE => cascade # fk_rails_... (user_id => users.id) ON DELETE => cascade ON UPDATE => cascade # class PollVote < ApplicationRecord belongs_to :user, optional: true belongs_to :option, class_name: 'PollOption', foreign_key: 'poll_option_id', inverse_of: :votes, optional: true has_one :poll, through: :option, foreign_key: 'poll_id' has_one :topic, through: :option # Make sure a user can only vote on the same option once validates :poll_option_id, uniqueness: { scope: :user_id } after_create :increase_counters after_destroy :decrease_counters def increase_counters option.increment! :vote_count poll.increment! :total_votes end def decrease_counters option.decrement! :vote_count poll.decrement! :total_votes end end