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

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

问题描述

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

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

对于(一个简单的)例子:

For (a trivial) example:

在用户模型中:

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天全站免登陆