添加评论+ Ajax

Dmy*_*sin 5 ajax ruby-on-rails

我已经开始学习rails了,我想在评论中添加ajax

应使用Ajax添加注释

你能帮忙或链接到一个例子吗?

这是我的config.rb:

  resources :posts do
    resources :comments
  end
Run Code Online (Sandbox Code Playgroud)

在post/show.html.erb中

<p><%= @post.title %></p>

    <h2>Comments:</h2>
    <div id='com'>
      <%= render @post.comments %>
    </div>

<h2>Add a comment:</h2>
<%= render "comments/form" %>
Run Code Online (Sandbox Code Playgroud)

在view/comments/_comment.html.erb中:

<p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
</p>
<p>
  <strong>Comment:</strong>
  <%= comment.body %>
</p>
<%= link_to "Del", [comment.post, comment], :confirm => 'Are you sure?', :method => :delete %>
<hr>
Run Code Online (Sandbox Code Playgroud)

在comments/form.html.erb中

<%= form_for([@post, @post.comments.build], remote: true) do |f| %>
.
.
.
Run Code Online (Sandbox Code Playgroud)

在comments_controller中:

class CommentsController < ApplicationController

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

    respond_to do |format|
        format.html { redirect_to post_path(@post) }
        format.js 
    end
  end
Run Code Online (Sandbox Code Playgroud)

并在视图中添加文件:_create.js.erb

$('#com').html("<%=j render @post.comments %>");
Run Code Online (Sandbox Code Playgroud)

没有远程true所有工作(但重新加载页面)动作删除工作

在application.html.erb中

  <%= javascript_include_tag 'application' %>
Run Code Online (Sandbox Code Playgroud)

当我点击提交表格 - 没有任何反应

但当我(提交后)重新加载页面 - 我看到添加了评论

Pri*_*ain 3

你需要包含不显眼的 javascript

app/assets/javascripts/application.js

你有这个吗(如果没有的话添加它)

//= require jquery
//= require jquery_ujs
Run Code Online (Sandbox Code Playgroud)

由 @DemitriyDN 本人回答:)

重命名_create.js.erbcreate.js.erb