Rails:在验证过程中惊慌失措是否不合适(除了例外)?
您有一个肺
模型。在其中,您输入:
validates_presence_of : human_id
您的应用的用户无法控制是否设置 human_id
;应用程序应该自动执行此操作。
如果 : human_id
曾经不存在,它不会帮助您的用户告诉他们“这个肺不是附着在人类身上”,因为您的用户不会能够对此做任何事情。你的模型是不是该惊慌失措并抛出异常了?
您的模型是否应该关心给定验证错误的严重性?这是业务逻辑的一部分吗?模型是否应该在验证期间抛出异常,或者控制器是否应该负责解释模型中的“哑”验证并为视图生成有用的数据?
编辑:如果这是可以接受的事情,那么在模型验证期间是否有关于如何抛出异常的约定?
You have a Lung
model. In it, you put:
validates_presence_of :human_id
Users of your app have no control over whether or not human_id
is set; the application should be doing it automatically.
If :human_id
were ever not present, it doesn't help your users to tell them "this lung isn't attached to a human", because your users won't be able to do anything about it. Is it time for your model to freak out and throw an exception?
Should your models ever care about the severity of a given validation error? Is that part of business logic? Should models ever throw exceptions during validation, or should the controllers be responsible to interpreting the "dumb" validation from the model and generating useful data for the view?
Edit: If this is an acceptable thing to do, are there any conventions regarding how to throw exceptions during a model's validation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我将设置 ActiveRecord 迁移,以便
human_id 列不能为
null 。这样,如果未设置,您无论如何都会得到异常。
I would set up my ActiveRecord migration so that the
human_id
column cannot benull
. That way you'd get an exception anyway if it's not set.我认为应该将其作为例外提出。在大多数情况下,应用程序都会放置 human_id,只有在特殊情况下, human_id 可能不存在,例如后端精心设计的请求或定时注销。由于这些是特殊情况,因此值得抛出异常而不是让控制器处理它。
I think it should be raised as a exception. The Application would be putting the human_id in most of the cases and only in exceptional cases the human_id might not be present, like say an crafted request or timed logout in the backend. Since these are exceptional cases it's worthwhile to throw exceptions instead of letting the controller handle it.
根据我的理解,验证不是检查这种模型一致性的正确位置。验证仅适用于用户生成的输入。
问题是:如果没有人类身份,怎么可能创造出肺呢?如果答案只能通过编程顺序来解决,那么您应该修复该错误并为其创建一些测试用例。或者,如果您确实想每次都检查它,您可以在 before_save 回调中检查它。
In my understanding validations are not the right place to check this kind of model consistency. Validations are only for user generated input.
The question is: how would it be possible that a Lung is created without a human id? If the answer is only through a programming order, you should propably fix that bug and create some test cases for it. Or if you really want to check it every time, you could check it inside a before_save callback.