Does Rails require database-level restrictions?

I have the same problem as in the next post .

So, I wonder why Rails does not support creating foreign keys by default? Is it not necessary? Or should we do it manually?

+23
ruby-on-rails foreign-keys foreign-key-relationship auto-generate
Apr 7 2018-10-10T00:
source share
2 answers

Database restrictions are not required anymore than wearing seat belts in your car. You can get around anything you like and everything will work just fine until the problem comes up. A seat belt (restriction) allows you (data) to be safe.

Therefore, it is strongly recommended that you create restrictions to ensure data integrity at the database level, since it is very likely that 1) you will interact with the database at some point outside of Rails, and 2) you will make an error in your code that causes invalid data.

Database restrictions can be more useful, but it saves a lot of work, especially when your code can make assumptions about data and don't have to do tons of validation checks.

The reason ActiveRecord does not support foreign keys out of the box is because it is designed for database agnostic, and foreign keys are not universally supported by all database systems.

+56
Apr 07 2018-10-10T00:
source share

You can add foreign key support using the Foreigner plugin.

Not all supported databases for ActiveRecord support foreign keys, so the Rails framework does not include it as a primary feature.




Note: the above is not more accurate since Rails added FK support in 4.2.

+9
Apr 07 '10 at 1:48 on
source share



All Articles