【发布时间】:2014-02-07 19:06:25
【问题描述】:
如何通过 Rails 迁移创建新表并为其添加唯一索引?
在文档中,我发现了如何在创建表后为其添加索引,但是您如何在同一个迁移文件中同时创建表和添加唯一索引?
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-4
如何通过 Rails 迁移创建新表并为其添加唯一索引?
在文档中,我发现了如何在创建表后为其添加索引,但是您如何在同一个迁移文件中同时创建表和添加唯一索引?
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-4
这是完整的过程:
生成迁移(rails generate migration CreateFoos bar:string 或 rails g 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
【讨论】:
更紧凑的方式:
class CreateFoobars < ActiveRecord::Migration
def change
create_table :foobars do |t|
t.string :name, index: {unique: true}
end
end
end
【讨论】:
生成迁移后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
【讨论】:
在 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)
【讨论】: