我试图提交一个“空白”表单,故意触发错误.
但是,它仍然响应“成功”功能而不是标记错误.但是,没有添加任何记录.
当我在输入字段中提交信息时,表单可以正常工作.
形成:
<%= simple_form_for :course,:url => {:action => 'create'},:remote => true do |f| %> <%= f.input :title %> <%= f.submit "Submit" %> <% end %>
模型:
class Course < ActiveRecord::Base validates :title,presence: true end
控制器:
def create @course = Course.new(course_params) respond_to do |format| if @course.save format.html { redirect_to(:controller => 'schedule',:action => 'index') } format.js else format.html { render :action => "new" } format.js end end end
create.js.erb
$(document).ready(function() { $("form").on("ajax:success",function(e,data,status,xhr) { alert("Success!"); }).bind("ajax:error",xhr,error) { alert("Error!"); }); });
共享/ error_messages.html.erb
<% if object && object.errors.size > 0 %> <div id="errorExplanation"> <h2><%= pluralize(object.errors.size,"error") %> prohibited this record from being saved.</h2> <p>There were problems with the following fields:</p> <ul> <% object.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %>
我在这里做错了什么想法?谢谢!
解决方法
你不需要在你的js.erb文件中有document.ready.你可以这样做
调节器
if @result = @course.save ..
create.js.erb
<% if @result %> alert("Success!"); <% else %> $('#error-div').html('<%= j(render :partial => 'shared/error_messages',:object => @course) %>'); <% end %>