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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With