【发布时间】:2015-06-18 16:11:20
【问题描述】:
我有一个 ajax 调用,当我点击 upvote/downvote 按钮(应该是 POST http 请求)时触发。但是,AJAX 正在返回一个内部 500 错误(我推测是因为没有投票视图文件)
控制器文件
class PostsController < ApplicationController
def vote
PostsVote.create(
user_id: session[:id],
post_id: vote_params[:post_id].to_i,
vote: vote_params[:vote].to_i)
@post = Post.find(vote_params[:post_id])
votes_total = @post.posts_votes.sum(:vote)
{post_id: @post.id, votes: votes_total}.to_json
end
private
def vote_params
params.permit(:post_id, :vote)
end
end
使用 AJAX 查看文件
<div class="container">
<h1>Welcome to Hacker News Clone</h1>
<h3>All posts</h3>
<ul>
<% @posts.each_with_index do |post, index| %>
<li id="post<%= post.id %>">
<a href="/posts/<%= post.id %>"><%= post.post_desc %>
</a>
<br/>
<span>
<%= @post_votes[index] %> points
</span>
by <a href="/users/<%= post.user.id %>"><%= post.user.username %></a> | <%= post.comments.count %> comments
<br/>
<button <%= "disabled" if post.posts_votes.find_by(user_id: session[:id]) && post.posts_votes.find_by_user_id(session[:id]).vote == 1 %> class="upvote" data-post-id="<%= post.id %>" width="40px" height="40px">Upvote</button>
<button <%= "disabled" if post.posts_votes.find_by(user_id: session[:id]) && post.posts_votes.find_by_user_id(session[:id]).vote == -1 %> class="downvote" data-post-id="<%= post.id %>" width="40px" height="40px">Downvote</button>
</li>
<br/>
<% end %>
</ul>
</div>
<script>
$(document).ready(function() {
// Check if any post-vote combination for that user already exists and change upvote/downvote button to disabled
$(".upvote").on("click", function(event) {
event.preventDefault();
var postId = $(this).data("post-id");
var url = "/posts/" + postId + "/vote"
$.ajax({
type: "POST",
url: url,
data: {"post_id": postId,
"vote": 1},
dataType: "json"
}).done(function(response){
debugger
$("#post" + response["post_id"] + " span").text(response["votes"] + " points");
$("#post" + response["post_id"] + " button" + ".upvote").attr("disabled", "disabled")
});
});
$(".downvote").on("click", function(event) {
event.preventDefault();
var postId = $(this).data("post-id");
var url = "/posts/" + postId + "/vote"
$.ajax({
type: "POST",
url: url,
data: {"post_id": postId,
"vote": -1},
dataType: "json"
}).done(function(response){
$("#post" + response["post_id"] + " span").text(response["votes"] + " points");
$("#post" + response["post_id"] + " button" + ".downvote").attr("disabled", "disabled")
});
});
});
</script>
任何帮助将不胜感激。
【问题讨论】:
-
检查您的日志文件 (
log/development.log)。您可以在基于 unix 的系统中使用$ tail -f log/development.log跟踪日志。您还可以在网络检查器中检查响应的正文。 Rails 在开发环境中包含有用的错误消息。
标签: jquery ruby-on-rails ruby ajax