Files
nairobi/app/controllers/comments/votes_controller.rb
taitus f87a332c3e Refactoring: Move 'vote' action to Comments::VotesControllers
As far as possible I think the code is clearer if we use CRUD actions
rather than custom actions. This will make it easier to add the action
to remove votes in the next commit.

Note that we are adding this line as we need to validate it that a vote
can be created on a comment by the current user:

```authorize! :create, Vote.new(voter: current_user, votable: @comment)```

We have done it this way and not with the following code as you might
expect, as this way two votes are created instead of one.

```load_and_authorize_resource through: :comment, through_association: :votes_for```

This line tries to load the resource @comment and through the association
"votes_for" it tries to create a new vote associated to that debate.
Therefore a vote is created when trying to authorise the resource and
then another one in the create action, when calling @comment.vote.
2023-10-09 07:21:49 +02:00

27 lines
779 B
Ruby

module Comments
class VotesController < ApplicationController
load_and_authorize_resource :comment
before_action :authenticate_user!
before_action :verify_comments_open!
def create
authorize! :create, Vote.new(voter: current_user, votable: @comment)
@comment.vote_by(voter: current_user, vote: params[:value])
respond_to do |format|
format.js { render :show }
end
end
private
def verify_comments_open!
return if current_user.administrator? || current_user.moderator?
if @comment.commentable.respond_to?(:comments_closed?) && @comment.commentable.comments_closed?
redirect_to polymorphic_path(@comment.commentable), alert: t("comments.comments_closed")
end
end
end
end