我正在我正在构建的应用程序上实现一个向上投票系统非常类似于stackoverflow上的应用程序。 当用户点击upvote或downvote时,会向我的一个控制器发送一个ajax请求,他们会更新几个表。 完成后,我使用respond_to路由到执行jquery的js.erb文件来更新用户显示。 但是,jquery没有被执行。 当我舔upvote / downvote时,控制器代码正确执行(我可以在rails控制台中看到它),但用户显示不会更新。 刷新后,用户显示更新,但不是异步。 我知道jquery没有在fire bug控制台中执行b / c我可以看到我的jquery代码 – 它只是没有被应用。 这是我的upvote控制器代码:
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-').html("upvote"); // this normally renders a partial (below), but I am rendering "upvote" until I can fix this // escape_javascript( 'post_voting', :locals => { post: @post, user_vote: @user_vote } %>)
这是我的HTML:
<div class="post_actions" id='post-action-' > 'post_voting', :locals => { post: post, user_vote: current_user.votes.where( post_id: post.id ).first } %>