Create index with migration shorthand in Rails
Using the Ruby on Rails migration generator is great to get up and running but always seems to require just a little bit more effort once the migration file is created.
There is a shorthand syntax for the cli interface of the generator but I can never remember it past a column name and type... so I'm putting this here to remember it for all of us!
To create an index just continue adding a bit more information to your column declaration. Let's start with this as a base so we're on the same page:
rails generate add_name_to_widgets name
This will create this migration:
class AddNameToWidgets < ActiveRecord::Migration[7.0]
def change
add_column :widgets, :name, :string
end
end
Now by making a minor adjustment to the original cli call we can generate the index too:
rails generate add_name_to_widgets name:string:index
class AddNameToWidgets < ActiveRecord::Migration[7.0]
def change
add_column :widgets, :name, :string
add_index :widgets, :name
end
end
And you know what? We can do unique indexes as well:
rails generate add_name_to_widgets name:string:uniq
class AddNameToWidgets < ActiveRecord::Migration[7.0]
def change
add_column :widgets, :name, :string
add_index :widgets, :name, unique: true
end
end