How to define a "unique" constraint on a column of MySQL table in Ruby on Rails 3?

Misha Moroshko picture Misha Moroshko · Dec 10, 2010 · Viewed 13.7k times · Source

I have a simple MySQL table with one column: name.

I would like to define a unique constraint on this column.

I can do:

class MyModel < ActiveRecord::Base
  validates_uniqueness_of :my_column_name
end

but it will work only at the application level, not at the database level.

What would you suggest ?

Answer

Eric Wanchic picture Eric Wanchic · Jul 2, 2012

Add a unique constraint to the database itself using:

add_index :my_models, :my_column_name, unique: true

...through a migration (and you might want to make that my_column_name not accept any null values too:

class CreateMyModels < ActiveRecord::Migration
  def change
    create_table :my_models do |t|
      t.string :my_column_name, null: false

      t.timestamps
    end

    add_index :my_models, :my_column_name, unique: true

  end
end