Reputation: 111
I am working with the voting button and try to post the ajax in RoR but cannot get through it.
Kindly check my route controller and the ajax as follows:
post 'post/vote' => 'votes#create'
class VotesController < ApplicationController
def create
vote = Vote.new
post_id = params[:post_id]
vote.post_id = params[:post_id]
vote.account_id = current_account.id
existing_vote = Vote.where(account_id: current_account.id, post_id: post_id)
respond_to do |format|
format.js do
if existing_vote.size > 0
existing_vote.first.destroy
else
@success = if vote.save
true
else
false
end
@post = Post.find(post_id)
@total_upvotes = @post.upvotes
@total_downvotes = @post.downvotes
end
end
end
end
$(function () {
$(".vote").on("click", ".upvote", function () {
let post_id = $(this).parent().data("id");
console.log("clicked " + post_id);
$.ajax({
url: "post/vote",
type:'POST',
data: { post_id: post_id },
success: function(){
console.log("success");
}
});
});
});
NoMethodError (undefined method `id' for nil:NilClass):
app/controllers/votes_controller.rb:6:in `create'
Started POST "/post/vote" for ::1 at 2021-02-27 12:58:29 +0700
Processing by VotesController#create as */*
Parameters: {"post_id"=>"2"}
Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.0ms | Allocations: 1234)
NoMethodError (undefined method `id' for nil:NilClass):
app/controllers/votes_controller.rb:6:in `create'
What I want at this point is to log the "success" why the error POST http://localhost:3000/post/vote 500 (Internal Server Error) appears and when I try to go to the http://localhost:3000/post/vote it shows No route matches [GET] "/post/vote" when trying to post ajax.
Upvotes: 0
Views: 277
Reputation: 11915
Looks like current_account
is nil
. Add the following code to VotesController
to make sure the user is authenticated.
before_action :authenticate_account!
The authenticate_account!
method will get called for every action defined in the controller.
Upvotes: 1