Stafford Brooke

i build things with text, eat tacos, and race myself

Rails 4: add_reference - Clean up your foreign key migrations

Yesterday when I was looking through the Edge Rails Migration Guides I noticed the addition of add_reference. add_refernce makes it easier to create migrations for foreign keys.

In a Rails 3 the code to add a foreign key and an index for that key would look something like:

    class AddCategoryToWidgets < ActiveRecord::Migration
      def change
        add_column :widgets, :category_id, :integer
        add_index :widgets, :category_id
      end
    end

In Rails 4 using add_reference we can simplify this code to:

    class AddCategoryToWidgets < ActiveRecord::Migration
      def change
        add_reference :widgets, :category, index: true
      end
    end

While this isn’t a game changing improvement, I feel like it does raise my “quality of life” as a Rails developer just a little bit. Happy coding!