Adding index :unique to a column in ruby on rails via generate migration

只谈情不闲聊 提交于 2019-12-03 08:45:50

问题


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:


Starting from Rails 3.2 you able to use:

 rails g migration add_index_to_table_name column_name:uniq

example from http://guides.rubyonrails.org/3_2_release_notes.html

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

upd I'm sorry. The default type if you don't pass it would be string. You can pass type by yourself.

column_name:type:uniq

Thus your example should looks like:

rails g migration add_index_to_customers customerID:integer:uniq


来源:https://stackoverflow.com/questions/16446814/adding-index-unique-to-a-column-in-ruby-on-rails-via-generate-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!