我有一个表单来创建约会对象,目标是:创建方法。成功创建对象后,我希望方法用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.save
为true
时,应用程序会使用html模板正确响应。但当它的false
rails仍然需要一个html模板(忽略format: 'js'
)时:
Missing template appointments/new, application/new with {:locale=>[:es], :formats=>[:html],..}
知道怎么做到这一点吗?
PS:表格没有遥控器:true
答案 0 :(得分:0)
在这种情况下,您希望使用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模板。