通过生成迁移将索引:唯一添加到 ruby​​ on rails 中的列 [英] Adding index :unique to a column in ruby on rails via generate migration

查看:20
本文介绍了通过生成迁移将索引:唯一添加到 ruby​​ on rails 中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that i can touch a migration and add

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

但是正确的 rails 迁移命令是如何生成这个的呢?

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

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

是吗?

在我的特殊示例中,我有一张客户表

In my special example I have a table customers

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

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

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

有什么想法或建议吗?

推荐答案

从 Rails 3.2 开始你可以使用:

Starting from Rails 3.2 you able to use:

 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}

更新对不起.如果您不通过,默认类型将是字符串.你可以自己传类型.

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

这篇关于通过生成迁移将索引:唯一添加到 ruby​​ on rails 中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆