Does Rails need database-level constraints?

前端 未结 2 484
醉话见心
醉话见心 2020-12-05 07:43

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 su

2条回答
  •  -上瘾入骨i
    2020-12-05 08:15

    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.

提交回复
热议问题