2013-05-14 148 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