通过生成迁移,在Ruby on Rails中为列添加索引:unique

27
我知道我可以接触到一个迁移并添加。
add_index :table_name, :column_name, :unique => true

但是正确的Rails迁移命令是什么来生成这个?

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

这是正确的吗?

在我的特殊例子中,我有一个名为“customers”的表格。

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

我想将客户ID设置为唯一的。尝试过了。

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

但是,如果我在完成后查看我的迁移文件,它并不正确,看到这个:

def change
    add_column :customers, :, :customerID,
    add_column :customers, :, :unique
    add_column :customers, :=, :string
  end
任何想法或建议?

确保在您的shell中不要使用> true,否则将通过重定向创建一个true文件。 - Joe Atzberger
1个回答

50

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

 rails g migration add_index_to_table_name column_name:type:uniq
  • 正常情况下,类型默认为字符串

Rails指南示例

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

回答问题

rails g migration add_index_to_customers customerID:integer:uniq

2
不行,那个不起作用。尝试使用以下代码:def change add_column :customerids, :customerID, :string add_index :customerids, :customerID, :unique => true end - Denny Mueller
尝试使用 rails g migration add_index_to_customers customerID:uniq,但仍将customerID创建为字符串。 - Denny Mueller
我已经添加了更多的示例。您可以将类型传递到迁移中。 - ck3g
是的,这很有帮助...为这个奇怪的添加数据类型做一个新问题。 - Denny Mueller
2
应该使用 add_index_to_table_name 而不是 add_index_to_column_name。 - Tabrez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接