回复'js'仅当请求有错误时(否则使用html)
respond with 'js' only if request has errors (otherwise use html)
我有一个表单来创建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.save
为true
时,应用程序将使用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模板。
相关文章:
- 回复'js'仅当请求有错误时(否则使用html)
- 我的html有一些错误
- 表单已发送,但验证有错误
- 如果文件不存在,fs.watch是否有错误处理程序
- 为什么我的 JavaScript 会导致 HTML 验证错误
- 文件下载html与错误处理FileNotFound
- Jquery prepend html语法错误“;和'
- Meteor上有错误的同步问题
- Javascript;html:有没有一种方法可以找到一个顶级的命名窗口(或选项卡)并将其带到前台,而不是将url加载到
- 表单验证:如果有错误,不要't使手风琴动起来
- 错误的内部 HTML 在错误的地方
- 在 HTML 页面错误之前加载 Javascript
- 我有错误文档.注册元素未被细化
- 如何转换为特定于 json 的类 c#?我有错误
- 如果当前输入有错误或警告,则禁用所有下一个表单输入字段
- 通过有错误的 Ajax-Request 打印出 HTML 会阻止进一步的 JS 工作
- 脸书应用程序有错误
- 将 gulp 与捆绑包一起使用时出错 - HTML 解析错误
- XDomainRequest 总是有错误
- HTML5 Canvas游戏有错误,点击时第一个拼图块会变成不同的块