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

newUserNameHere picture newUserNameHere · Feb 7, 2014 · Viewed 34.3k times · Source

How do I create a new table, through a rails migration, and add an unique index to it?

In the docs I found how to add a index to a table after it's been created, but how do you do both -- create the table, and add the unique index -- in the same migration file?

Answer

newUserNameHere picture newUserNameHere · Feb 7, 2014

Here's the full process:

Generate a migration ( rails generate 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