我正在使用 Rails 4.2.3 和“:remote => true”属性远程提交表单。但是,我无法显示返回的验证错误。在我的控制器中,我有
def create
@my_object = MyObject.new(my_object_params)
@current_user = User.find(session["user_id"])
@my_object.user = @current_user
@date = Date.strptime(my_object_params[:day], "%m/%d/%Y")
@my_object.day = @date
respond_to do |format|
if @my_object.save
flash[:notice] = 'Saved successfully'
format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }
format.js { render js: "window.location='/users'" }
else
format.html { render action: "index" }
format.json { render json: @my_object.errors, status: :unprocessable_entity }
format.js { render json: { error: @my_object.errors, success: false }, content_type: 'application/json' }
end
end
end
在我的咖啡脚本中,我有
$(document).ready (data) ->
$("#add_form").bind "ajax:error", (xhr, status, error) ->
console.log(xhr)
console.log(status)
console.log(error)
render_form_errors(xhr, error)
#Give an alert message
$("#add_form").bind "ajax:before", (evt, data, status, xhr) ->
hrs = $('#my_object_hour').val();
min = $('#my_object_minute').val();
sec = $('#my_object_second').val();
$('#my_object_my_object_times_attributes_0_time_in_ms').val((hrs * 60 * 60 + min * 60 + sec) * 1000);
但是“xhr、status、error”这三个字段都没有包含 JSON 错误。console.log 语句的输出是
j…y.Event {type: "ajax:error", timeStamp: 1465418664628, jQuery112103593207809583596: true, isTrigger: 3, namespace: ""…}
users.self-a27ba2c….js?body=1:13 Object {readyState: 4, responseText: "ArgumentError in MyObjectsController#create↵↵invalid d…VER_PROTOCOL: "HTTP/1.1"↵↵Response headers↵None↵↵", status: 500, statusText: "Internal Server Error"}
users.self-a27ba2c….js?body=1:14 error
如何从我的控制器传回这些信息?
谢谢, -
编辑:作为对答案的回应,我以指定的方式编辑了我的控制器,并将其添加到我的咖啡脚本中......
$(document).ready (data) ->
$("#add_form").bind "ajax:failure", (e, xhr, status, error) ->
console.log('error');
console.log(e);
console.log(xhr);
console.log(status);
console.log(error);
render_form_errors(xhr, error)
$("#add_form").bind "ajax:error", (xhr, status, error) ->
console.log(xhr)
console.log(status)
console.log(error)
render_form_errors(xhr, error)
#Give an alert message
$("#add_form").bind "ajax:before", (evt, data, status, xhr) ->
hrs = $('#my_object_hour').val();
min = $('#my_object_minute').val();
sec = $('#my_object_second').val();
hrs_in_ms = hrs * 60 * 60 * 1000
min_in_ms = min * 60 * 1000
sec_in_ms = sec * 1000
ms = hrs_in_ms + min_in_ms + sec_in_ms
alert(ms)
$('#my_object_my_object_times_attributes_0_time_in_ms').val(ms);
但是在提交我的表单时出现错误,以上都没有被调用。我知道有错误,因为我看到(通过调试)“if @my_object.save”的“else”子句被调用。