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?
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.
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.
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.
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?
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With