Javascript Rails 4:在ajax中发布和评论索引操作
我尝试在我的索引操作中创建一个简单的Post/Comment函数,但我也尝试在ajax中实现它(目前,在注释上,但我得到了以下错误: ActionView::Template::Error(未定义的局部变量或方法'comment' 这是我的档案: 注释\u controller.rbJavascript Rails 4:在ajax中发布和评论索引操作,javascript,jquery,ruby-on-rails,ruby,ajax,Javascript,Jquery,Ruby On Rails,Ruby,Ajax,我尝试在我的索引操作中创建一个简单的Post/Comment函数,但我也尝试在ajax中实现它(目前,在注释上,但我得到了以下错误: ActionView::Template::Error(未定义的局部变量或方法'comment' 这是我的档案: 注释\u controller.rb def create @posts = Post.includes(:comments).order("created_at DESC") @comment = current_us
def create
@posts = Post.includes(:comments).order("created_at DESC")
@comment = current_user.comments.new(comment_params)
respond_to do |format|
if @comment.save
format.js {render 'posts/create'}
else
redirect_to :back
end
end
end
def index
@posts = Post.includes(:comments).order("created_at DESC")
@comment = Comment.new
@post = Post.new
end
index.html.erb
<% @posts.each do |post| %>
<tr>
<td><%= post.user.email %></td>
<td><%= post.content %></td>
<% post.comments.each do |comment| %>
<div id="comment">
<%= render :partial => 'comment_ajax', :locals => { :comment => comment } %>
</div>
<% end %>
<%= form_for @comment, remote: true do |f| %>
<%= f.text_field :content %>
<%= f.submit %>
<% end %>
<% end %>
<%= comment.content %>
routes.rb
resources :posts
resources :comments
create.js.erb
$("#comment").html("<%= escape_javascript(render :partial => 'posts/comment_ajax', :locals => { :comment => comment }) %>");
$(“#comment”).html('posts/comment_ajax',:locals=>{:comment=>comment})%>”;
_注释_ajax.html.erb
<% @posts.each do |post| %>
<tr>
<td><%= post.user.email %></td>
<td><%= post.content %></td>
<% post.comments.each do |comment| %>
<div id="comment">
<%= render :partial => 'comment_ajax', :locals => { :comment => comment } %>
</div>
<% end %>
<%= form_for @comment, remote: true do |f| %>
<%= f.text_field :content %>
<%= f.submit %>
<% end %>
<% end %>
<%= comment.content %>
我知道这是因为我的create.js.erb文件中有“:locals=>{:comment=>comment}”,但我无法理解
谢谢!你试过
:locals=>{:comment=>@comment}create.js.erb
中的本地人?好的……它似乎起作用了!谢谢!但是现在我在显示新内容时遇到了问题,我想这是我的问题。谢谢!我无法理解新问题。#comment
div的内容应该被创建的注释内容替换。哦,是你吗想要append()
而不是html()
?我从未见过在这种情况下使用appendHtml(),是吗?它应该是append()
而不是appendHtml()
,在注释中更正。如果您试图将新注释附加到\comment
div中,那么可以使用append()
,如果要替换#comment
div的内容,请使用html()
。