Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) ===================
like image 938
Michael Durrant Avatar asked Jan 25 '26 12:01

Michael Durrant


1 Answers

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.

like image 169
Doon Avatar answered Jan 28 '26 04:01

Doon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!