How to Create a New Table With a Unique Index in an Active Record / Rails 4 Migration

Here's the full process:

Generate a migration ( rails generate migration CreateFoos bar:string or rails g migration CreateFoos bar:string )

Modify your migration to look something like this:

class CreateFoos < ActiveRecord::Migration
  def change
    create_table :foos do |t|
      t.string :bar, :null => false

      t.index :bar, unique: true
    end
  end
end

Run rake db:migrate


A more compact way:

class CreateFoobars < ActiveRecord::Migration
  def change
    create_table :foobars do |t|
      t.string :name, index: {unique: true}
    end
  end
end

After generating a migration rails generate migration CreateBoards name:string description:string

In the migration file, add index as shown below:

class CreateBoards < ActiveRecord::Migration
  def change
   create_table :boards do |t|
     t.string :name
     t.string :description

     t.timestamps
   end

   add_index :boards, :name, unique: true

 end
end