Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign keys with Rails' ActiveRecord::Migration?

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?

like image 912
Earlz Avatar asked Apr 03 '10 22:04

Earlz


People also ask

How do you add references to migration?

When you already have users and uploads tables and wish to add a new relationship between them. Then, run the migration using rake db:migrate . This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table), PLUS it will also add an index on the new column.

How do I migrate a specific migration in rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.

How does rails know which migration to run?

Rails uses this timestamp to determine which migration should be run and in what order, so if you're copying a migration from another application or generate a file yourself, be aware of its position in the order. This generator can do much more than append a timestamp to the file name.


2 Answers

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?

like image 200
mikewilliamson Avatar answered Oct 26 '22 07:10

mikewilliamson


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).

like image 37
glebm Avatar answered Oct 26 '22 07:10

glebm