我在我的 Rails 博客中添加了 ajax。它只适用于一个帖子,但在我添加下一个之后发生了一些奇怪的事情。我在同一页面上获得了我的帖子的副本。
Comments_controller.rb
class CommentsController < ApplicationController
def create
@posts = Post.all
@post = Post.find(params[:post_id])
@comment = @post.comments.create!(params[:comment])
respond_to do |format|
format.html {redirect_to @post}
format.js
end
end
end
index.html.erb
<%= render 'post' %>
创建.js.erb
$('.post').html("<%= escape_javascript(render("posts/post")) %>") });
_post.html.erb
<% @posts.each do |post| %>
<div class="post">
<p><strong> <%= post.title %> </strong>, posted <%= post.created_at.to_date %> </p> <br />
<%= post.content %> <br />
<%= simple_form_for [post, post.comments.build], :remote => true do |f| %>
<%= f.input :content %>
<%= f.button :submit %>
<% end %>
<%= render :partial => 'comment', :locals => {:post => post} %>
</div>
<% end %>
_comment.html.erb
<div class = "comment">
<ol>
<% post.comments.each do |comment| %>
<li> <%= comment.content %></li>
<% end %>
</ol>
</div>