28

I know that i can touch a migration and add

add_index :table_name, :column_name, :unique => true

But how is the right rails migration command to generate this?

rails g migration add_index_to_column_name :column_name, :unique => true

Is that right?

In my special example I have a table customers

  t.integer :customerID
  t.string :surname
  t.string :first_name
  t.string :phone

an i want to set the customerID to unique. Tried

rails g migration AddIndexToCustomers :customerID, :unique => true 

But if i look to my migration file after this, it dont look right see this:

def change
    add_column :customers, :, :customerID,
    add_column :customers, :, :unique
    add_column :customers, :=, :string
  end

Any idea or suggestion?

1
  • Make sure not to use > true in your shell, or you'll create a true file via redirection. Commented Apr 27, 2017 at 0:31

1 Answer 1

51

Starting from Rails 3.2 you able to use:

 rails g migration add_index_to_table_name column_name:type:uniq
  • as normal, type defaults to string

Rails guide example

 rails g scaffold Post title:string:index author:uniq price:decimal{7,2}

Answer to the question

rails g migration add_index_to_customers customerID:integer:uniq
Sign up to request clarification or add additional context in comments.

5 Comments

nope.. thats not working getting def change add_column :customerids, :customerID, :string add_index :customerids, :customerID, :unique => true end
tried rails g migration add_index_to_customers customerID:uniq but still creates the customerID as a string.
I've added more examples. You can pass type into migration.
yeah this helps... doing new question for this strange adding the datatype
It should be add_index_to_table_name not add_index_to_column_name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.