I’ve been looking into Foreigner to see if this will help us with our foreign key issues and I am liking it so far! Here’s what I’ve found:
Foreigner can be installed as either a plugin or a gem and provides us with methods that we can use in our migrations for adding and removing foreign keys. A great thing about Foreigner is that it works with both PostgreSQL and MySQL. This differs from the MigrationHelpers class we currently use, which was designed to work with PostgreSQL only. Migrations that use Foreigner will also work on databases that do not support foreign keys (eg. sqlite3).
There are a couple of different ways foreign keys can be specified in a migration:
- If we want to specify that there should be a foreign key from the GradeEntryItem table to the GradeEntryForm table, we could add the following line:
add_foreign_keymethod can also take some options. For example, we could include the :dependent option as follows:
add_foreign_key(:grades, :grade_entry_items, :dependent => :destroy)
- Alternatively, foreign keys can be specified as part of the
t.foreign_keytakes the same options as
create_table :grades do |t|
With Foreigner, we’ll even be able to see the foreign keys in schema.rb!
It seems like Foreigner would provide us with a simple, straight-forward way of adding foreign keys to our migration files. I’ve installed the plugin on my machine and am going to try it out to see how it works.
Fixtures and foreign keys
One thing to keep in mind is that the order in which fixtures are loaded becomes important when foreign keys are involved. Things can start to get kind of tricky. This is why alternatives to fixtures (like factory_girl) are good things to investigate.