2012-08-09 99 views
0

我正在實現一個應用程序的增值投票系統,我正在建立非常類似於這裏在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) 
+0

爲了記錄,那不是你得到的任何錯誤! – pahnin 2013-09-20 08:00:00

回答

0

搞亂了jquery後,我注意到了一些東西。首先,我需要縮小我的代碼(取出所有評論和未使用的空間)。我把這個:

$('#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 } %>) 

,並把它改成這樣:

$('#post-action-<%= @post.id %>').html("upvote"); 

的代碼,然後工作,並且用戶顯示正在更新,以顯示「給予好評」。完善。於是我用這個替換了上面的代碼:

$('#post-action-<%= "#{@post.id}" %>').html("<%= escape_javascript(render :partial => 'post_voting', :locals => { :post => @post, :user_vote => @user_vote }) %>"); 

和KAPOW!有用。很高興能解決這個問題!減少你的JQUERY人!

0

你的代碼似乎確定,應該執行。您可能會執行額外的檢查來更新固定ID而不是計算出的ID。

$('#updateme').html("upvote"); 

並將此ID添加到您的HTML某處。如果這樣,你確定ajax-call完全執行,而問題只是你引用的id。

你有沒有檢查過你的html源碼有一個id「post-action-2」?

+0

是的,遺憾的是我的html中有一個'id =「post-action-2」' – flyingarmadillo 2012-08-09 13:17:42