通过生成迁移向 ruby​​ on rails 中的列添加索引 :unique

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16446814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:56:58  来源:igfitidea点击:

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

ruby-on-railsdatabaseruby-on-rails-3.2migration

提问by Denny Mueller

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 迁移命令是如何生成这个的呢?

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

我想将 customerID 设置为唯一的。试过

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?

有什么想法或建议吗?

回答by ck3g

Starting from Rails 3.2 you able to use:

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

 rails g migration add_index_to_table_name column_name:uniq

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

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

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

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

upd对不起。如果你不传递它的默认类型将是字符串。你可以自己传递类型。

column_name:type:uniq

Thus your example should looks like:

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

rails g migration add_index_to_customers customerID:integer:uniq