views:

563

answers:

3

Hello, I'm new to Ruby on Rails (I know Ruby just decently though) and looking at the Migration tools, it sounds really awesome. Database schemas can finally (easily) go in source control.

Now my problem with it. When using Postgres as the database, it does not setup foreign keys. I would like the benefits of foreign keys in my schema such as referential integrity. So how do I apply foreign keys with Migrations?

+4  A: 

Check this out: http://github.com/matthuhiggins/foreigner

But first make sure you really need them (e.g. referential integrity is something that theoretically shouldn't break as long as your code is OK, and you know about :dependent => :destroy and the difference between user.delete and user.destroy).

glebm
Well, I'm thinking not only about referential integrity, but also on the speed benefits of foreign keys whenever you join 2 key'd tables.
Earlz
@Earlz, I know this is a big can of worms in the rails community but if you're using mysql, it seems like a no-brainer. This plugin works awesomely. `FK in Rails == HAPPY` :)
macek
+3  A: 

Rails philosophy is that integrity checks is business logic that belongs in the model. Thats why you are seeing what you are seeing in the DB; whatever_id is just an int and not a "real" fk in sight. Its not a mistake, its by design and its a little freaky at first. Generally the only reason that drives people to work with fks in the DB level is when the DB is accessed by more than one app or its a legacy system. There is plenty of discussion and some great links here: http://stackoverflow.com/questions/928425/why-do-rails-migrations-define-foreign-keys-in-the-application-but-not-in-the-dat

Mike Williamson
Well, my goal is a new project, and no other app will be accessing it.. so maybe I don't need it? It feels weird though lol
Earlz
It does feel weird. Eventually you see the sense of it though. To address your speed concern below, you should make a point of using the add_index command in your migrations. An fk adds an index to the database automatically. In Rails you just add them yourself as needed... If you remember :)
Mike Williamson
A: 

There are a number of plugins available (search google) for Rails that will create foreign keys for you when you use a special symbol in your migrations (foreign_key_migrations is one from the Advanced Rails Recipes book). Just be aware that Rails does not play well with this concept especially when you are trying to delete objects (as mentioned by glebm).

simianarmy