Ajax 使用 rails 4.0 发布用于评论论坛线程



我正在使用rails 4.0开发一个简单的论坛应用程序。我希望我的评论以 Ajax 的形式发布,而不是重新加载整个页面,请帮助我。这是我的节目.html.erb 论坛

 <div id="topic_content">
  <h1>
   <%= @topic.title %>
  </h1>
  <p>
    <%= @topic.content %>
  </p>
  <div id="comments">
   <h2>
    <%= @topic.comments.count %>
    Comments
   </h2>
   <%= render @topic.comments %>
   <%if user_signed_in? && current_user.user? %>
   <h3>Reply to thread</h3>
   <%= render "comments/form" %>
  <% end %>
 </div>
 <br/>
 <hr/>
 <br/>
 <%if user_signed_in?%>
 <% if can? :update, @topic %>
  <%= link_to "Edit", edit_topic_path(@topic), class: "button" %> 
 <% end %>

<% if can? :delete, @topic %>
 <%= link_to "Delete", topic_path(@topic), method: :delete, data: {      confirm: "Are you sure you want to do this?" }, class: "button" %>
<% end %>
<% end %>
</div>

这是我的_comment.html.erb部分

<div class="comment clearfix">
<div class="content">
 <p class="comment_content">
   <%= comment.comment %>
 </p>
</div>
<div class="buttons">
<%if user_signed_in?%>
<% if can? :update, @topic => Comment %>
  <%= link_to "Edit", edit_topic_comment_path(comment.topic, comment) %>
<% end %>
<% if can? :delete, @topic => Comment %>
  <%= link_to "Delete", [comment.topic, comment], method: :delete, data: { confirm: "Are you sure?" } %>
  <% end %>
<% end %>
</div>

您可以使用服务器生成的JavaScript和远程表单。

  1. 向表单添加remote: true
  2. 准备控制器以使用 JavaScript 进行响应:

    # CommentsController
    def create
      @comment = @topic.comments.create!(comment_params)
      respond_to do |format|
        format.html { redirect_to @comment } # no js fallback
        format.js   # renders comments/create.js.erb
      end
    end
    
  3. 创建create.js.erb模板:

    # comments/create.js.erb
    $('#comments').prepend('<%=j render @comment %>');
    

    这里发生的事情是,我们告诉 Rails 将我们的注释(使用注释部分)渲染为 JavaScript 就绪字符串(注意<%=j),我们正在创建 JS,它将在commentsdiv 的开头预置这个新注释。尝试一下您可以使用此JS响应做什么;它是在带有表单的页面上下文中运行的,因此您可以从中获得很多乐趣。

另请阅读 https://signalvnoise.com/posts/3697-server-generated-javascript-responses 的文章 - 这是我学习这种技术的地方,您无疑会发现您的案例的示例代码与其示例代码之间的相似之处。

最新更新