AutomaticForeignKey allows you to create foreign keys easier than ever.

Particularly lots of migrations doesn’t need any change. Let’s dive into it quickly.

class CreateGroups < ActiveRecord::Migration
  def self.up
    create_table :groups do |t|
      t.string :name, :null => false, :limit => 50
      t.integer :user_id, :null => false

      t.timestamps :null => false
    end
  end

  def self.down
    drop_table :groups
  end
end

In that case we’ll have foreign key on groups(user_id) referencing users(id).

But wait a moment. This one looks like ordinary migration. Where did you define foreign key? Well, automatic_foreign_key is smart enough to be predict that user_id column should be referenced to users(id).

Obviously we could customize the behaviour.

    # force user_id to reference admins table
    t.integer :user_id, :null => false, :references => :admins
    # don't create foreign key on application_id column
    t.integer :application_id, :references => nil

It’s dead easy, isn’t it?

If you want to see more just go to github page or start using it now!

$ gem install automatic_foreign_key

Let’s take a look at what brings version 1.2 to us.

Rails 3 generator

New generator creates automatic_foreign_key initializer:

$ rails g automatic_foreign_key:install
  create  config/initializers/automatic_foreign_key.rb

Currently 3 options are supported:

  • on_update - default ON UPDATE action (available options are :cascade, :restrict, :set_null, :set_default, :no_action)
  • on_delete - default ON DELETE action (available options as above)
  • auto_index - automatically create indexes on foreign keys

Fixed auto-index when restoring schema

Previously restoring schema may have led to duplicated indexes. Currently the problem is solved.

Upgraded to RSpec 2

Specs are compatible with Rspec 2.4.0.

Bundler instead of Jeweler

Gemspec is maintained by bundler. You can read more about this change on my blog post.

WrocLove.rb