Ruby on Rails:最好在模型或数据库中验证吗? [英] Ruby on Rails: Is it better to validate in the model or the database?

查看:99
本文介绍了Ruby on Rails:最好在模型或数据库中验证吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常是更好的做法(以及为什么)在模型或数据库定义中验证属性。

Is it generally better practice (and why) to validate attributes in the model or in the database definition?

对于一个简单的例子:

在用户模型中:

validates_presence_of :name

与迁移相比:

t.string :name, :null => false 

一方面,将其包含在数据库中似乎更能​​保证防止任何类型的坏数据偷偷摸摸。另一方面,将它包含在模型中使事情更透明和更容易理解,通过将其分组在代码中与其余的验证。我也考虑做这两个,但这似乎都不干燥,不太可维护。

On the one hand, including it in the database seems more of a guarantee against any type of bad data sneaking in. On the other hand, including it in the model makes things more transparent and easier to understand by grouping it in the code with the rest of the validations. I also considered doing both, but this seems both un-DRY and less maintainable.

推荐答案

我强烈建议地方。在模型中执行此操作会为您保存一个数据库查询(可能通过网络),这将基本上出错,并在数据库中执行此操作,以保证数据的一致性。

I would highly recommend doing it in both places. Doing it in the model saves you a database query (possibly across the network) that will essentially error out, and doing it in the database guarantees data consistency.

这篇关于Ruby on Rails:最好在模型或数据库中验证吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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