A migration to add unique constraint to a combination of columns A migration to add unique constraint to a combination of columns ruby-on-rails ruby-on-rails

A migration to add unique constraint to a combination of columns


add_index :people, [:firstname, :lastname, :dob], :unique => true


According to howmanyofme.com, "There are 46,427 people named John Smith" in the United States alone. That's about 127 years of days. As this is well over the average lifespan of a human being, this means that a DOB clash is mathematically certain.

All I'm saying is that that particular combination of unique fields could lead to extreme user/customer frustration in future.

Consider something that's actually unique, like a national identification number, if appropriate.

(I realise I'm very late to the party with this one, but it could help future readers.)


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  endend

There are different constraints you can add. Read the docs