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

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

问题描述

我遇到了与 以下帖子.

所以我想知道,为什么 Rails 默认不支持生成外键?没有必要吗?还是我们应该手动完成?

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.

因此强烈建议您创建约束以在数据库级别强制执行数据完整性,因为很可能 1)您将在 Rails 之外的某个时间点与数据库交互,以及 2)您会在您的导致无效数据的代​​码.

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.

ActiveRecord 不支持开箱即用外键的原因是因为它与数据库无关,而且并非所有数据库系统都普遍支持外键.

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