Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby rails generate migration commond to add Index on multiple columns in Ruby on Rails

I'm new Ruby on Rails. I trying to add index on multiple columns in the existing project. Over the internet I see examples that it can be added as shown below. But I'm not able to understand how to generate migrate script to add the index. Any help would be appreciate.

add_index :facility_user_assignments, [:facility_id, :user_id], unique: true.

Below is what I found over internet. How can this be changed to add to multiple columns

rails generate migration AddIndexToPhoneToUsers phone:string:uniq

Thanks in advance.

like image 691
sg_developer Avatar asked Oct 15 '25 15:10

sg_developer


2 Answers

use:

rails generate migration addIndicesToPhone phone:string:uniq

Then go to your migration file 'add_indices_to_phone.rb' and add what wever fields you want before you migrate.

class AddIndicesToPhone < ActiveRecord::Migration
  def change
    add_column :phone, :string
    add_column :another_field, :string # add these fields manually
  end

  add_index :phone, :phone, unique: true
  add_index :phone, :another_field, unique: true  # add these fields manually
end

I hope this is what you are looking for.

like image 70
gordonturibamwe Avatar answered Oct 18 '25 07:10

gordonturibamwe


Most migrations cannot be generated via the CLI. Instead you should just generate an empty migrate, and fill in the change method by hand.

rails generate migration AddIndexToPhoneToUsers
like image 20
meagar Avatar answered Oct 18 '25 07:10

meagar



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!