Does Rails need database-level constraints?
Asked Answered
P

2

24

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?

Provost answered 7/4, 2010 at 1:46 Comment(0)
F
59

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.

Forbis answered 7/4, 2010 at 3:46 Comment(2)
I like the seat-belt analogy !Dutyfree
Another reason: unless your Rails app is one process, one thread, running on a single server, it may process multiple requests at once. Things like validates :username, uniqueness: true can fail in that case, because each app instance checks for the requested username, doesn't find it, and inserts it. Only a unique index prevents that. In general, any check like "is this data valid given what's in the database right now?" can only be reliably done by the database itself.Metempirics
K
9

You can add foreign-key support with the Foreigner plugin.

Not all of the supported databases for ActiveRecord support foreign keys, so the Rails framework doesn't include it as a core feature.


Note: the above is no longer accurate, as Rails added FK support in 4.2.

Kathrinekathryn answered 7/4, 2010 at 1:48 Comment(1)
The short answer is, yes it's important but by default you have to use the :options hash. ActiveRecord lives at a level of abstraction where it can't assume support for FKs.Kathrinekathryn

© 2022 - 2024 — McMap. All rights reserved.