我的堆栈跟踪显示Rendered comments/create.js.erb (4.0ms)
,但alert('test');
未执行(代码下方也没有)。这是为什么?
堆栈跟踪
Started POST "/articles/6/comments" for 127.0.0.1 at 2014-05-25 14:45:07 -0400
Processing by CommentsController#create as JS
Parameters: {"utf8"=>"✓", "comment"=>{"author"=>"six", "body"=>"six"}, "commit"=>"Create Comment", "article_id"=>"6"}
(0.1ms) begin transaction
SQL (1.8ms) INSERT INTO "comments" ("article_id", "author", "body", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["article_id", 6], ["author", "six"], ["body", "six"], ["created_at", Sun, 25 May 2014 18:45:07 UTC +00:00], ["updated_at", Sun, 25 May 2014 18:45:07 UTC +00:00]]
(1.7ms) commit transaction
Article Load (0.2ms) SELECT "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT 1 [["id", "6"]]
Comment Load (0.3ms) SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = 6
Rendered comments/_list_comments.html.erb (2.1ms)
Rendered comments/create.js.erb (4.0ms)
Completed 200 OK in 22ms (Views: 8.0ms | ActiveRecord: 4.1ms)
_form.html.erb
<%= simple_form_for [@article, @comment], remote: true do |f| %>
<%= f.input :author, required: false %>
<%= f.input :body, required: false %>
<%= f.button :submit %>
<% end %>
comments_controller.rb
class CommentsController < ApplicationController
def create
@comment = Comment.new(comment_params)
@comment.article_id = params[:article_id]
if @comment.save
respond_to do |f|
f.html { redirect_to article_path(@comment.article_id), notice: 'Comment created!' }
f.js {
@article = Article.find(params[:article_id])
@comment = @comment
@comments = Comment.where(article_id: params[:article_id])
}
end
else
respond_to do |f|
f.html { redirect_to article_path(@comment.article_id), warning: 'Unable to create comment.' }
f.js {
@article = Article.find(params[:article_id])
@comment = @comment
@comments = Comment.where(article_id: params[:article_id])
}
end
end
end
private
def comment_params
params.require(:comment).permit(:author, :body)
end
end
create.js.erb
alert('test');
$("#comments_listing").html(<%= j render 'comments/list_comments' %>);
_list_comments.html.erb
<div id="comments_listing">
<% @comments.each do |comment| %>
<hr />
<p><small><%= comment.author %></small></p>
<p><%= comment.body %></p>
<% end %>
</div>
答案 0 :(得分:1)
您应该查看浏览器上呈现的内容。
但我认为错误是您应该像这样调用html方法:
$("#comments_listing").html("<%= j render('comments/list_comments') %>");
如果您不添加引号,则脚本将失败。