How to Create a New Table With a Unique Index in an Active Record / Rails 4 Migration

前端 未结 5 1899
生来不讨喜
生来不讨喜 2021-02-01 12:41

How do I create a new table, through a rails migration, and add an unique index to it?

In the docs I found how to add a index to a table after it\'s been created, but h

5条回答
  •  醉话见心
    2021-02-01 13:10

    In Rails 5, you can provide index options along with column definition.

    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)
    
    

提交回复
热议问题