Ruby-on-rails 如何在 Active Record / Rails 4 迁移中创建具有唯一索引的新表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21635825/
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
How to Create a New Table With a Unique Index in an Active Record / Rails 4 Migration
提问by newUserNameHere
How do I create a new table, through a rails migration, and add an unique index to it?
如何通过 rails 迁移创建一个新表,并为其添加唯一索引?
In the docs I found how to add a index to a table after it's been created, but how do you do both -- create the table, and add the unique index -- in the same migration file?
在文档中,我找到了如何在创建表后向表添加索引,但是您如何在同一个迁移文件中同时执行这两项操作——创建表并添加唯一索引?
回答by newUserNameHere
Here's the full process:
这是完整的过程:
Generate a migration ( rails generate migration CreateFoos bar:string)
生成迁移 ( rails generate migration CreateFoos bar:string)
Modify your migration to look something like this:
将迁移修改为如下所示:
class CreateFoos < ActiveRecord::Migration
def change
create_table :foos do |t|
t.string :bar, :null => false
t.index :bar, unique: true
end
end
end
Run rake db:migrate
跑 rake db:migrate
回答by AkaZecik
A more compact way:
更紧凑的方式:
class CreateFoobars < ActiveRecord::Migration
def change
create_table :foobars do |t|
t.string :name, index: {unique: true}
end
end
end
回答by Kirti Thorat
After generating a migration rails generate migration CreateBoards name:string description:string
生成迁移后 rails generate migration CreateBoards name:string description:string
In the migration file, add index as shown below:
在迁移文件中,添加索引如下图:
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
回答by Randomtheories
You can create the table and index with the generator without changing the migration file
您可以在不更改迁移文件的情况下使用生成器创建表和索引
For a unique index
对于唯一索引
rails generate model CreateFoos bar:string:uniq
For a non-unique index
对于非唯一索引
rails generate model CreateFoos bar:string:index
回答by Akanksha Sharma
In Rails 5, you can provide index options along with column definition.
在 Rails 5 中,您可以提供索引选项以及列定义。
create_table :table_name do |t|
t.string :key, null: false, index: {unique: true}
t.jsonb :value
t.timestamps
end
Column | Type | Collation | Nullable | Default
------------+-----------------------------+-----------+----------+-----------------------------------------
id | bigint | | not null | nextval('table_name_id_seq'::regclass)
key | character varying | | not null |
value | jsonb | | |
created_at | timestamp without time zone | | not null |
updated_at | timestamp without time zone | | not null |
Indexes:
"table_name_pkey" PRIMARY KEY, btree (id)
"index_table_name_on_key" UNIQUE, btree (key)

