Ruby-on-rails – Foreign keys with Rails’ ActiveRecord::Migration

foreign-keysmigrationpostgresqlruby-on-rails

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?

Best Answer

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: Why do Rails migrations define foreign keys in the application but not in the database?