2015-05-02 23 views
0

我已經在表格文章和文章的Rails中構建了一個應用程序。這個想法是當我在帖子的頁面時,我可以查看與此帖子相關的所有評論並添加新評論。在添加W/O頁面更新後,新的評論立即出現在頁面上。問題是,當我通過ajax創建評論時,他們沒有出現在頁面 - 我需要更新它。我不明白爲什麼會這樣Ruby on Rails Ajax請求不會在沒有頁面更新的情況下出現

create.js.erb

var new_comment = $("<%= escape_javascript(render(:partial => @comment))%>").hide(); 
$('#comments').prepend(new_comment); 
$('#comment_<%= @comment.id %>').fadeIn('slow'); 
$('#new_comment')[0].reset(); 

我的展後頁面的評論是

<p id="notice"><%= notice %></p> 

<p> 
    <strong>Title:</strong> 
    <%= @post.title %> 
</p> 

<p> 
    <strong>Body:</strong> 
    <%= @post.body %> 
</p> 

<h2>Comments</h2> 
<div id="comments">  
    <%= render :partial => @post.comments.reverse %> 
</div> 

<%= form_for([@post, Comment.new], remote: true) do |f| %> 
    <p><%= f.label :body, "New Comment" %><br /> 
     <%= f.text_area :body %> 
    </p> 
    <p><%= f.submit "Add Comment" %></p> 
<% end %> 

<%= link_to 'Edit', edit_post_path(@post) %> | 
<%= link_to 'Back', posts_path %> 

我創建行動

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.create(comment_params) 

    respond_to do |format| 
     if @comment.save 
     format.html { redirect_to @post, notice: 'Comment was successfully created.' } 
     format.json { render :show, status: :created, location: @comment } 
     format.js #create.js.erb 
     else 
     format.html { render :new } 
     format.json { render json: @comment.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

和我_comment.html.erb文件

<%= div_for comment do %> 
     <p> 
     <strong>Posted <%= time_ago_in_words(comment.created_at) %></strong><br /> 
     <%= h(comment.body) %> 
     </P> 
    <% end %> 

能否請你幫我看看哪裏出了問題,可以嗎? 非常感謝您提前!

+0

你從ajax得到什麼迴應(如果你檢查螢火蟲或鉻開發工具) – jphager2

+0

當我按下「添加評論」 - 我看到POST請求和沒關係。然後,在「刷新」後,我得到了幾個GET請求,部分是確定的,部分是304「未修改」錯誤,它們也有緩存控制字段「無緩存」......如果這有幫助......或者我應該尋找什麼? – Nastya

+0

對不起,我想我以前的回答不是你問我的。因爲當我不使用ajax時,我得到了GET請求的相同部分,其中一些是正確的,有些則具有相同的錯誤。不同之處在於在按下「添加註釋」之後POST和GET請求一起「自動」生成,沒有刷新 – Nastya

回答

0

我發現後顯示頁面中的印刷錯誤 - 被寫成「commetns」而不是「評論」。現在一切正常,因爲它應該 @ jphager2,謝謝你的幫助

相關問題