回复'js'仅当请求有错误时(否则使用html)

respond with 'js' only if request has errors (otherwise use html)

本文关键字:html 有错误 js 请求 回复      更新时间:2023-09-26

我有一个表单来创建Appointment对象,目标是:create方法。当对象成功创建时,我希望方法用html响应,但如果不是,我想用js响应。这就是我所做的:

def create
  appointment = Appointment.new(appointment_params)
  if appointment.save
    redirect_to appointment_path(appointment)
  else
    @errors = appointment.errors
    redirect_to new_appointment_path, format: 'js'
  end
end

appointment.savetrue时,应用程序将使用html模板进行正确响应。但当它是false时,rails仍然需要一个html模板(忽略format: 'js'):

Missing template appointments/new, application/new with {:locale=>[:es], :formats=>[:html],..}

知道如何做到这一点吗?

PS:表单没有remote:true

在这种情况下,您希望使用Rails ism来避免呈现丢失的HTML模板:

def create
  appointment = Appointment.new(appointment_params)
  if appointment.save
    redirect_to appointment_path(appointment) and return
  else
    @errors = appointment.errors
    redirect_to new_appointment_path, format: 'js' and return
  end
end

redirect_to调用之后,您需要从函数中调用return,这样Rails就不会自动尝试为操作呈现HTML模板。