Michael Durrant
Michael Durrant

Reputation: 96484

Rails migration for multi-column index - how can I name the index?

This adds the index but doesn't let me set the name. How can I do that?

class AddIndexEventScheduleidDayStarttime < ActiveRecord::Migration
  def up
    add_index(:events, [:schedule_id, :day , :start_time], {:name => "event_schedule_by_day_and_time_index"})
  end 

  def down
    remove_index(:events, {name: "event_schedule_by_day_and_time_index"})
  end 
end

$ rake db:migrate
==  AddIndexEventScheduleidDayStarttime: migrating ============================
-- add_index(:events, [:schedule_id, :day, :start_time], {:name=>"event_schedule_by_day_and_time_index"})
   -> 0.2210s
==  AddIndexEventScheduleidDayStarttime: migrated (0.2212s) ===================

Upvotes: 3

Views: 2691

Answers (1)

Doon
Doon

Reputation: 20232

if you look at the docs (http://api.rubyonrails.org/classes/ActiveRecord/Migration.html) you will see that add_index is add_index(table_name, column_names, options)

so writing your code as follows:

  def up
    add_index(:events,[:schedule_id, :day , :start_time],name: "event_schedule_by_day_and_time_index")
  end

should be what you want. The options come after the column ids.

Upvotes: 8

Related Questions