# frozen_string_literal: true # == Schema Information # # Table name: post_votes # # up :boolean not null # created_at :datetime not null # post_id :bigint not null, primary key # user_id :bigint not null, primary key # # Indexes # # index_post_votes_on_post_id_and_user_id (post_id,user_id) UNIQUE # index_post_votes_on_user_id (user_id) # # Foreign Keys # # fk_rails_... (post_id => posts.id) # fk_rails_... (user_id => users.id) ON DELETE => restrict ON UPDATE => cascade # class Post::Vote < ApplicationRecord # This class is not to be used directly for voting - see VotingEngine instead! self.primary_keys = :post_id, :user_id belongs_to :post belongs_to :user validates :post, presence: true validates :user, presence: true after_create do user.inc_stat(:votes_cast) end after_destroy do user.dec_stat(:votes_cast) end # Ghetto counter cache # before_save do # post.with_lock do # chg_upvotes = -post.votes.where(user: user, up: true).delete_all # chg_upvotes += 1 if up # chg_downvotes = -post.votes.where(user: user, up: false).delete_all # chg_downvotes += 1 if !up # # post.update_columns( # score: post.score + chg_upvotes - chg_downvotes, # upvotes_count: post.upvotes_count + chg_upvotes, # downvotes_count: post.downvotes_count + chg_downvotes, # updated_at: Time.zone.now # ) # end # end # before_destroy do # post.with_lock do # chg_upvotes = 0 # chg_upvotes = -1 if up # chg_downvotes = 0 # chg_downvotes = -1 if !up # # post.update_columns( # score: post.score + chg_upvotes - chg_downvotes, # upvotes_count: post.upvotes_count + chg_upvotes, # downvotes_count: post.downvotes_count + chg_downvotes, # updated_at: Time.zone.now # ) # end # end end