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

前端 未结 5 1900
生来不讨喜
生来不讨喜 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:27

    After generating a migration 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
    

提交回复
热议问题