A migration to add unique constraint to a combination of columns

前端 未结 6 442
你的背包
你的背包 2020-11-29 17:40

What I need is a migration to apply unique constraint to a combination of columns. i.e. for a people table, a combination of first_name, last

6条回答
  •  孤独总比滥情好
    2020-11-29 18:18

    You may want to add a constraint without an index. This will depend on what database you're using. Below is sample migration code for Postgres. (tracking_number, carrier) is a list of the columns you want to use for the constraint.

    class AddUniqeConstraintToShipments < ActiveRecord::Migration
      def up
        execute <<-SQL
          alter table shipments
            add constraint shipment_tracking_number unique (tracking_number, carrier);
        SQL
      end
    
      def down
        execute <<-SQL
          alter table shipments
            drop constraint if exists shipment_tracking_number;
        SQL
      end
    end
    

    There are different constraints you can add. Read the docs

提交回复
热议问题