添加索引:通过生成迁移,在rails上的ruby中的列是唯一的

我知道我可以触摸迁移并添加

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

但正确的rails migration命令如何生成呢?

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

是对的吗?

在我的特例中,我有一个表客户

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

我想将customerID设置为唯一。 试着

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

但是,如果我在此之后查看我的迁移文件,它看起来不正确看到这个:

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

有什么想法或建议吗?

从Rails 3.2开始,您可以使用:

  rails g migration add_index_to_table_name column_name:uniq 

示例来自http://guides.rubyonrails.org/3_2_release_notes.html

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

我很抱歉。 如果不传递默认类型,则为string。 你可以自己传递类型。

 column_name:type:uniq 

因此,您的示例应如下所示:

 rails g migration add_index_to_customers customerID:integer:uniq