Today I Learned

hashrocket A Hashrocket project

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
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.