我试图在我的 ajax 表单中显示错误消息(代码基于这个问题):
post_controller.rb:
def create
@post = current_user.posts.build(params[:post])
if params[:commit] == "Publish"
@post.status = "Published"
elsif params[:commit] == "Save Draft"
@post.status = "Draft"
end
respond_to do |format|
format.html do
if @post.save && @post.status == "Published"
flash[:success] = "Post published"
redirect_to @post
elsif @post.save && @post.status == "Draft"
flash[:success] = "Post saved as draft"
render 'edit'
else
render 'new'
end
end
format.js do
@post.save
end
end
end
帖子/create.js.erb:
<% if @post.errors.any? %>
alert('There are errors.');
<%= render :partial=>'js_errors', :locals=> { :target=> @post } %>
<% else %>
$('.busy').html('Saved.');
<% end %>
js_errors.js.erb:
<% target.errors.full_messages.each do |error| %>
$('.busy').append('<p><%= escape_javascript( error ) %></p>');
<% end %>
帖子/new.html.erb:
<%= form_for(@post, remote: true, :html => { :multipart => true }) do |f| %>
<%= render 'fields', f: f %>
<div class="form-actions">
<%= f.submit "Publish", class: "publish btn btn-primary pull-left" %>
<%= f.submit "Save Draft", class: "save-draft btn btn-default pull-left" %>
<div class="busy pull-left">
</div>
</div>
<% end %>
但由于某种原因,什么都没有显示(.busy
始终保持空白)。
在控制台中,我可以看到js_errors.js.erb
正在显示:
在 2013-01-04 18:02:18 +0800 开始 POST "/posts" for 127.0.0.1 由 PostsController#create as JS 参数处理:{"utf8"=>"✓", "authenticity_token"=>"Qfn6HsPPDxyB1t4bM/ OQKPbJ/aoAMkp74y0Z6xkoXCY=", "post"=>{"title"=>"", "content"=>"", "tag_list"=>""}, "_wysihtml5_mode"=>"1", "commit"= >"Save Draft"} 用户负载 (0.7ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'ljl0ZsuoiHg0Jilz8bgy-g' LIMIT 1 (0.2ms) 开始事务
(0.2ms) 回滚事务渲染的帖子/_js_errors.js.erb (3.8ms) 渲染的帖子/create.js.erb (7.5ms)在 25ms 内完成 200 OK(查看:11.2ms | ActiveRecord:1.0ms | Solr:0.0ms)
可能是什么问题呢?
(如果我remote:true
从表单中删除,我确实会看到验证消息)。
编辑:
我注意到alert('There are errors.');
没有被触发。奇怪的。