如何在Active Record / Rails 4迁移中创建具有唯一索引的新表

如何通过rails迁移创建新表,并为其添加唯一索引?

在文档中,我发现如何在创建表后为表添加索引,但是如何在同一个迁移文件中同时创建表并添加唯一索引?

这是完整的过程:

生成迁移( rails generate migration CreateFoos bar:string

修改您的迁移,使其如下所示:

 class CreateFoos < ActiveRecord::Migration def change create_table :foos do |t| t.string :bar, :null => false t.index :bar, unique: true end end end 

运行rake db:migrate

生成迁移后, rails generate migration CreateBoards name:string description:string

在迁移文件中,添加索引,如下所示:

 class CreateBoards < ActiveRecord::Migration def change create_table :boards do |t| t.string :name t.string :description t.timestamps end add_index :boards, :name, unique: true end end 

您可以使用生成器创建表和索引,而无需更改迁移文件

对于一个独特的索引

 rails generate model CreateFoos bar:string:uniq 

对于非唯一索引

 rails generate model CreateFoos bar:string:index 

更紧凑的方式:

 class CreateFoobars < ActiveRecord::Migration def change create_table :foobars do |t| t.string :name, index: {unique: true} end end end