Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 287
Misha Moroshko Avatar asked Dec 10 '10 03:12

Misha Moroshko


1 Answers

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
like image 160
Eric Wanchic Avatar answered Oct 14 '22 08:10

Eric Wanchic