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

new*_*ere 36 activerecord ruby-on-rails ruby-on-rails-4

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

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

new*_*ere 61

这是完整的过程:

生成迁移(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
Run Code Online (Sandbox Code Playgroud)

rake db:migrate


Aka*_*cik 22

更紧凑的方式:

class CreateFoobars < ActiveRecord::Migration
  def change
    create_table :foobars do |t|
      t.string :name, index: {unique: true}
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


Kir*_*rat 10

生成迁移后 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
Run Code Online (Sandbox Code Playgroud)


Ran*_*ies 6

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

对于唯一索引

rails generate model CreateFoos bar:string:uniq
Run Code Online (Sandbox Code Playgroud)

对于非唯一索引

rails generate model CreateFoos bar:string:index
Run Code Online (Sandbox Code Playgroud)


小智 6

在 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)

Run Code Online (Sandbox Code Playgroud)