Search code examples
ruby-on-railsrubyruby-on-rails-4

Advanced usage of add_index


In my Ruby on Rails project I have migration that creates case insensitive index for string column.

class AddCeCodeToUsers < ActiveRecord::Migration
  def change
    add_column :users, :ce_code, :string

    execute <<-SQL
      CREATE UNIQUE INDEX index_users_on_lower_ce_code_index
        ON users USING btree (lower(ce_code));
    SQL
  end
end

This works as expected but I want to know is there any way to do the same using rails built_in add_index method?


Solution

  • For mysql try:

    add_index "users", "lower(ce_code)", name: "index_users_on_lower_ce_code"
    

    For PG try:

    install gem "schema_plus_pg_indexes"

    t.index expression: "lower(ce_code)", name: "index_users_on_lower_ce_code"