Skip to content
Snippets Groups Projects
Commit 5be016f0 authored by ArtOfCode-'s avatar ArtOfCode-
Browse files

Lock votes on deleted posts

parent e1e551b9
Branches
Tags
No related merge requests found
...@@ -11,7 +11,13 @@ class VotesController < ApplicationController ...@@ -11,7 +11,13 @@ class VotesController < ApplicationController
end end
destroyed = post.votes.where(user: current_user).destroy_all destroyed = post.votes.where(user: current_user).destroy_all
vote = post.votes.create!(user: current_user, vote_type: params[:vote_type].to_i, recv_user: post.user) vote = post.votes.create(user: current_user, vote_type: params[:vote_type].to_i, recv_user: post.user)
if vote.errors.any?
puts "hi"
render json: { status: 'failed', message: vote.errors.full_messages.join('. ') }, status: 403
return
end
modified = !destroyed.empty? modified = !destroyed.empty?
state = { status: (modified ? 'modified' : 'OK'), vote_id: vote.id, post_score: post.score } state = { status: (modified ? 'modified' : 'OK'), vote_id: vote.id, post_score: post.score }
...@@ -26,9 +32,11 @@ class VotesController < ApplicationController ...@@ -26,9 +32,11 @@ class VotesController < ApplicationController
render(json: { status: 'failed', message: 'You are not authorized to remove this vote.' }, status: 403) && return render(json: { status: 'failed', message: 'You are not authorized to remove this vote.' }, status: 403) && return
end end
vote.destroy! if vote.destroy
render json: { status: 'OK', post_score: vote.post.score } render json: { status: 'OK', post_score: vote.post.score }
else
render json: { status: 'failed', message: vote.errors.full_messages.join('. ') }, status: 403
end
end end
private private
... ...
......
...@@ -7,10 +7,12 @@ class Vote < ApplicationRecord ...@@ -7,10 +7,12 @@ class Vote < ApplicationRecord
after_create :apply_rep_change after_create :apply_rep_change
after_create :change_post_score after_create :change_post_score
before_destroy :check_valid
before_destroy :reverse_rep_change before_destroy :reverse_rep_change
before_destroy :restore_post_score before_destroy :restore_post_score
validates :vote_type, inclusion: [1, -1] validates :vote_type, inclusion: [1, -1]
validate :post_not_deleted
def self.total_rep_change(col) def self.total_rep_change(col)
col = col.includes(:post) col = col.includes(:post)
...@@ -56,4 +58,14 @@ class Vote < ApplicationRecord ...@@ -56,4 +58,14 @@ class Vote < ApplicationRecord
def restore_post_score def restore_post_score
post.update!(score: post.score - vote_type) post.update!(score: post.score - vote_type)
end end
def post_not_deleted
if post.deleted?
errors.add(:base, 'Votes are locked on deleted posts')
end
end
def check_valid
throw :abort unless valid?
end
end end
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment