我正在實現一個應用程序的增值投票系統,我正在建立非常類似於這裏在stackoverflow上的應用程序。當用戶點擊upvote或downvote,ajax請求被髮送到我的控制器之一,他們更新了幾個表。一旦完成,我使用respond_to路由到執行jquery的js.erb文件來更新用戶顯示。但是,jquery沒有被執行。當我舔了一下/ downvote,控制器代碼正確執行(我可以在rails控制檯中看到它),但用戶顯示不會更新。刷新後,用戶顯示屏會更新,但不是異步的。我知道jquery沒有在fire bug console中執行b/c,我可以看到我的jquery代碼 - 它只是沒有被應用。這是我給予好評控制器代碼:Rails jquery ajax請求不執行
def upvote
@post = Post.find(params[:id])
@user_vote = current_user.votes.where(post_id: @post.id).first
if @user_vote.blank?
Vote.create(user_id: current_user.id, post_id: @post.id, vote: 1)
@post.upvotes += 1
elsif @user_vote.vote.to_i == 0
@user_vote.vote = 1
@post.upvotes += 1
elsif @user_vote.vote.to_i == 1
return redirect_to :back, :alert => 'You have already upvoted the post'
elsif @user_vote.vote.to_i == 2
@user_vote.vote = 1
@post.downvotes -= 1
@post.upvotes += 1
end
respond_to do |format|
if @post.save and @user_vote.save
format.js { }
else
format.html { redirect_to :back, :alert => 'There was an error in upvoting the post' }
end
end
end
這是我upvote.js.erb文件:
$('#post-action-<%= @post.id %>').html("upvote");
// this normally renders a partial (below), but I am rendering "upvote" until I can fix this
// escape_javascript(<%= render :partial => 'post_voting', :locals => { post: @post, user_vote: @user_vote } %>)
這裏是我的html:
<div class="post_actions" id='post-action-<%= "#{post.id}" %>' >
<%= render :partial => 'post_voting', :locals => { post: post, user_vote: current_user.votes.where(post_id: post.id).first } %>
</div>
這裏是我的螢火控制檯輸出: http://i.imgur.com/H6zXJ.png
編輯
我注意到,我在我的服務器上得到一個錯誤:
Started GET "/assets/bootstrap.js?body=1" for 127.0.0.1 at 2012-08-09 06:33:42 -0700
Served asset /bootstrap.js - 304 Not Modified (0ms)
爲了記錄,那不是你得到的任何錯誤! – pahnin 2013-09-20 08:00:00