2013-05-14 193 views
0

對於我的應用程序,我有一些項目,用戶可以在其中發表評論(Newcomments類)貼子。現在它發佈很好,但頁面刷新。我正在嘗試使用AJAX/JQUERY,以便它不會刷新頁面。我正在關注這個railscasts教程。Rails - AJAX/JQuery不起作用

所以現在,這些帖子是對我的數據庫和頁面不刷新。但是,當我刷新時,帖子顯示。我爲特定項目呈現我的評論的頁面位於projects/_comments.html.erb上。

問題:我該如何調整它以使它對新評論進行渲染?

newcomments_controller.rb

def create 
    @newcomment = @commentable.newcomments.new(params[:newcomment]) 

    if @newcomment.save 
     respond_to do |format| 
      format.html { redirect_to comments_project_path(@commentable) } 
      format.js 
     end 
    else 
    render :new 
    end 
end 

視圖/ newcomments/_form.html.erb

<span class="comment"> 
<%= form_for [@commentable, @newcomment], remote: true do |f| %> 
    <%= f.text_area :content, rows: 3, :class => "span8" %> 
    <%= f.hidden_field :user_id, :value => current_user.id %> 
    <%= f.submit "Add Comment", :class => "btn btn-header" %>  
<% end %> 
</span> 

視圖/ newcomments/create.js.erb

$('#newcomment').append('<%= j render(@newcomments) %>'); 

projects_controller.rb

def comments 
    @commentable = @project 
    @newcomments = @commentable.newcomments.newest.page(params[:comments_page]).per_page(10) 
    @newcomment = Newcomment.new 

    respond_to do |format| 
    format.html # show.html.erb 
    format.json { render json: @project.comments } 
    end 
end 

項目/ comments.html.erb

<%= render 'comments' %> 

項目/ _comments.html.erb

<%= render @newcomments %> 

查看/ newcomments/_newcomment.html.erb

<div class="comments"> 
    <%= link_to newcomment.user.name %></strong> 
    Posted <%= time_ago_in_words(newcomment.created_at) %> ago 
    <%= newcomment.content %> 
</div> 

<span class="comment"> 
    <%= form_for [@commentable, @newcomment] do |f| %> 
     <div class="field"> 
     <%= f.text_area :content, rows: 3, :class => "span8" %> 
     </div> 

     <%= f.hidden_field :user_id, :value => current_user.id %> 

     <div class="actions"> 
     <%= f.submit "Add Comment", :class => "btn btn-header" %> 
     </div> 

    <% end %> 

    <% unless newcomment.newcomments.empty? %> 
     <%= render @newcomments %> 
    <% end %> 
</span> 

回答

0

嘗試結合AJAX的動作如下所述: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

此外,考慮返回渲染意見部分HTML而不是JSON註釋對象,這樣做你需要在形式之後告訴:remote指令:'data-type'=>'html',以便返回的html將命中AJAX成功綁定的函數,然後將容器div的html與例如jQuery