MarkUs Blog

MarkUs Developers Blog About Their Project

Foreigner Findings

with 2 comments

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_key(:grade_entry_items, :grade_entry_forms)
  • The add_foreign_key method 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 create_table statement (t.foreign_key takes the same options as add_foreign_key):
    • create_table :grades do |t|
      t.foreign_key :grade_entry_items

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.

Written by Farah Juma

November 11th, 2009 at 11:04 pm

Posted in Uncategorized

2 Responses to 'Foreigner Findings'

Subscribe to comments with RSS or TrackBack to 'Foreigner Findings'.

  1. Exactly! I’d be so happy if we could use factory_girl or whatever (instead of fixtures) in conjunction with Foreigner and most (if not all) the db trouble would be taken care of 🙂


    11 Nov 09 at 11:32 pm

  2. […] Looked into Foreigner and created a blog post on my findings […]

Leave a Reply