views:

171

answers:

3

If I am not wrong then Rails has its own foreign key logic implemented using ActiveRecord. Is that to help performance i.e. so that you don't rely on the database for the additional processing logic or make frequent database transactions? Or is it for some other reason?

+1  A: 

No, that is to avoid duplication. DRY. The foreign key relationship in the database is reflected in the application. There should be only one place where that relationship is described.

Stephan Eggermont
I understand the when foriegn key implementation is already there in Rails then why on database but the question was what are plus are what are the gains of having it at application level when compared to db level. Is it the performance?
Lakshmi
Developer performance.
Stephan Eggermont
Exacty as Stephan put it - if you have to configure/change only one place, you tend to get stuff done faster.
Toms Mikoss
+1  A: 

I would think it was about the robustness of the application.

A DBA can easily delete any foriegn key constraint leaving your app in a mess.

An attempt to insert will raise an SQL exception. If you have several foreign key constraints on a table it's a pain working out which column and value triggered the exception. It's much easier to check first and give the end user a menaingful^h^h^h^h^h^henacing^h^h^h^h^h^h^h^hmeaningful error message.

In large databases it's common practice to turn off foriegn key constaints both to speed up performance and to make maintenance, backup/recovery, and replication less error prone.

James Anderson
@James Thanks James.
Lakshmi
+1  A: 

Rails still uses foreign keys the same as normal. It's just that it doesn't enforce the use of foreign key constraints.

You can get by without using explicit foreign key constraints in the database, assuming you set up validations in your models to stop data corruption.

It is a form of duplication to define constraints, but I prefer it for maintaining data integrity. Even with ActiveRecord associations and validations defined, it's still too easy to mess up the data structure during migrations, or bulk updates etc. There are a number of plugins that make it easy to define your FKs DRYly as part of your normal ActiveRecord migrations

Also, even if you don't create FK constraints relationships, you'll still probably want to define at least an index on the foreign key so when you do something like post.comments you're not causing a full table scan to find all the comments with the matching post_id (when you define FK constraints, a lot of DBMSs do that implicitly for you).

madlep