处理错误验证时何时使用 render 与 redirect_to [英] When to use render vs redirect_to when handling error validations

查看:32
本文介绍了处理错误验证时何时使用 render 与 redirect_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当复杂的视图,它有多个表单、对这些表单、分页和其他功能的大量验证.当验证失败时,我喜欢使用渲染,因为这样您就可以更具体地了解表单中发生的错误.但是,当我使用渲染时,会出现不同的编译器错误,例如[]:Array 的未定义方法 `total_pages'"和未定义的模型名称".这是我必须使用 redirect_to 的情况,还是以某种方式解决呈现视图时出现的错误是否可行.非常感谢!

I have a fairly complex view that has multiple forms, lots of validations on those forms, paginations, and other features. When validations fail, I like to use render because then you can be more specific about what errors occurred in the forms. However, when I use render different compiler errors crop up such as "undefined method `total_pages' for []:Array" and "undefined model_name". Is this a situation when I have to use redirect_to or is it feasible to somehow work around the errors that are coming up when the view is being rendered. Thanks a bunch!

推荐答案

你应该从他们的角度来理解事情.

You should grasp things in their perspective.

为什么使用 render 而不是 redirect:

Why is render used instead of redirect:

  • 当你使用render时,你传递了实例化的对象

  • when you use render, you pass the instantiated object

这个新创建或更新的对象收到了一些参数

this object, newly created or updated, received some params

尝试保存对象时,触发了验证,如果不成功,则向当前实例添加错误

when attempting to save the object, validation was triggered and, if unsuccessful, added errors to the current instance

因此您内存中的对象包含验证错误.

so your object in memory contains validation errors.

但是当您使用重定向时,您会使用一个新堆栈重新启动,该堆栈对内存中的前一个对象一无所知,不可能有任何魔法:

But when you use redirect, you restart with a fresh stack which doesn't know anything about the former object in memory, there could not be any magic:

  • 要么保存对象,要么从数据库中获取持久化数据

  • either the object is saved and you can get the persisted data from database

或者如果它没有保存,你可以有一些你之前存储在会话中的信息

or if it's not saved, you can have some information you previously stored in session

更接近地回答您的问题:在使用渲染之前,您必须实例化页面所需的所有对象.

To answer your question a bit closer: before you use render, you have to instantiate all objects needed by the page.

如果缺少预期的实例变量,视图将失败只是逻辑.

It's just logic the view fails if the expected instance variables are missing.

这篇关于处理错误验证时何时使用 render 与 redirect_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆