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 ?
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