POST http://localhost:3000/post/vote 500(内部服务器错误) - 尝试在 Rails 中发布 ajax 时没有路由匹配 [GET] "/post/vote"



我正在使用投票按钮,并尝试在RoR中发布ajax,但无法通过它。

请检查我的路由控制器和ajax如下:

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'

我现在想要的是记录"成功"。为什么错误POST http://localhost:3000/post/vote 500(内部服务器错误)出现,当我试图去http://localhost:3000/post/vote时,它显示没有路由匹配[GET] "/POST/vote"当尝试发布ajax时。

看起来像current_accountnil。在VotesController中添加以下代码,以确保用户已通过身份验证。

before_action :authenticate_account!

authenticate_account!方法将被控制器中定义的每个动作调用。

最新更新