Change post votes to work the same way as comment votes: * Make the upvote arrow blue if you've upvoted the post, or grey if you haven't. Likewise for the downvote arrow. * Make it so you can click the upvote or downvote arrows to undo the vote. * Don't show any notices when you vote on a post. Also fix it so that votes work the same way on the posts page, the comments page, and in the modqueue. Before it wasn't possible to undo votes on the comments page or in the modqueue.
64 lines
1.5 KiB
Ruby
64 lines
1.5 KiB
Ruby
class PostVote < ApplicationRecord
|
|
class Error < StandardError; end
|
|
|
|
belongs_to :post
|
|
belongs_to :user
|
|
attr_accessor :vote
|
|
|
|
after_initialize :initialize_attributes, if: :new_record?
|
|
validates_presence_of :score
|
|
validates_inclusion_of :score, in: [1, -1]
|
|
after_create :update_post_on_create
|
|
after_destroy :update_post_on_destroy
|
|
|
|
scope :positive, -> { where("post_votes.score > 0") }
|
|
scope :negative, -> { where("post_votes.score < 0") }
|
|
|
|
def self.visible(user)
|
|
user.is_admin? ? all : where(user: user)
|
|
end
|
|
|
|
def self.search(params)
|
|
q = search_attributes(params, :id, :created_at, :updated_at, :score, :user, :post)
|
|
q.apply_default_order(params)
|
|
end
|
|
|
|
def initialize_attributes
|
|
self.user_id ||= CurrentUser.id
|
|
|
|
if vote == "up"
|
|
self.score = 1
|
|
elsif vote == "down"
|
|
self.score = -1
|
|
end
|
|
end
|
|
|
|
def is_positive?
|
|
score > 0
|
|
end
|
|
|
|
def is_negative?
|
|
score < 0
|
|
end
|
|
|
|
def update_post_on_create
|
|
if score > 0
|
|
Post.where(:id => post_id).update_all("score = score + #{score}, up_score = up_score + #{score}")
|
|
else
|
|
Post.where(:id => post_id).update_all("score = score + #{score}, down_score = down_score + #{score}")
|
|
end
|
|
end
|
|
|
|
def update_post_on_destroy
|
|
if score > 0
|
|
Post.where(:id => post_id).update_all("score = score - #{score}, up_score = up_score - #{score}")
|
|
else
|
|
Post.where(:id => post_id).update_all("score = score - #{score}, down_score = down_score - #{score}")
|
|
end
|
|
end
|
|
|
|
def self.available_includes
|
|
[:user, :post]
|
|
end
|
|
end
|