Rails是否需要数据库级的约束? [英] Does Rails need database-level constraints?

查看:189
本文介绍了Rails是否需要数据库级的约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有和是不是有必要?
或者我们应该手动完成这个工作吗?

你的车需要安全带。你可以驾驶你喜欢的一切,一切都会很好,直到问题到来。因此,强烈建议您在数据库级别创建约束来强制实现数据完整性,因为它是安全的(约束),使您的数据安全无虞。

很可能是这样的:1)你将在Rails之外的某个地方与数据库进行交互,2)你会在代码中犯一个错误,导致无效数据。



数据库约束可以做更多的工作,但是它可以节省大量的工作,特别是当你的代码可以对数据做出假设的时候,并且不需要进行大量的有效性检查。

ActiveRecord不支持外键的原因是因为它意味着与数据库无关,外键并不是所有数据库系统都支持的。


I have the same problem as in the following post.

So I am wondering, why doesn't Rails support generating foreign keys by default? Isn't it necessary? Or are we supposed to do it manually?

解决方案

Database constraints aren't required any more than wearing seat-belts are required in your car. You can drive around all you like and everything will work great until a problem arrives. The seat-belt (constraints) keep you (the data) safe.

So it's highly recommended that you create constraints to enforce data-integrity at the database level, because it's highly likely that 1) You will interact with the database at some point outside of Rails and 2) You will make a mistake in your code that causes invalid data.

Database constraints can be more work, but it saves a lot of work, especially when your code can make assumptions about the data and doesn't have to do tons of validity checks.

The reason ActiveRecord doesn't support foreign keys out of the box is because it is meant to be database-agnostic, and foreign keys are not universally supported by all database systems.

这篇关于Rails是否需要数据库级的约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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