Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 714
newUserNameHere Avatar asked Feb 07 '14 19:02

newUserNameHere


3 Answers

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

like image 65
newUserNameHere Avatar answered Oct 09 '22 13:10

newUserNameHere


A more compact way:

class CreateFoobars < ActiveRecord::Migration
  def change
    create_table :foobars do |t|
      t.string :name, index: {unique: true}
    end
  end
end
like image 60
AkaZecik Avatar answered Oct 09 '22 13:10

AkaZecik


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
like image 17
Kirti Thorat Avatar answered Oct 09 '22 13:10

Kirti Thorat