views:

186

answers:

3

Hi,

I'm developing some things in Ruby on Rails, and I've currently got several models with relationships between them. Now, the models specify the relations, so I know that RoR will enforce integrity, but what about at the DB level ?

Do other people set up foreign key relationships in DB tables ? and if so, how ?, there doesn't seem to be any way to setup/destroy a db relationship in a migration (maybe using raw SQL)

Thanks

Paul.

A: 

There isn't a way to do it from the migration short of using SQL, which means that:

  1. It's DB-specific
  2. You have to use SQL

The first isn't really that big a deal (how often do you switch databases on a project anyway?), and the second is simply a fact of life. So, use them if you want.

Pesto
A: 

Incidentally these things should always be set up at the database level. There are other ways to access and change data in the database besides the application. You should never set these types of rules in the application unless you want useless data. All things that touch on data integrity must be at the database level even if you have to (GASP) use SQL.

HLGEM
not always. There are scenarios were setting foreign-keys on the db is the best answer, but on most web applications I've worked, it was not necessary; while having such business rules on the application level makes a lot of sense.
Maximiliano Guzman
+2  A: 

Here's a guide on how to do it: http://seb.box.re/2006/7/29/foreign-key-and-rails-migration

There is also a plugin for this here: http://github.com/harukizaemon/foreign_key_migrations/tree/master

However, Rails does not easily support foreign keys in migrations for a reason. Basically they're not really necessary when using ActiveRecord.

Here's a good explanation of why they are not necessary and their usage is discouraged in rails: http://www.motionstandingstill.com/i-dont-use-foreign-key-constraints-with-rails/2008-10-17/

Opinions differ on this subject. There's a good discussion here: http://forum.softiesonrails.com/forums/3/topics/138

Gdeglin