How to define a "unique" constraint on a column of MySQL table in Ruby on Rails 3?
Solution 1
This is not super-helpful, but it looks like there is not a great answer for enforcing uniqueness at the database level. From the Rails migration guide:
The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database, are not heavily used.
Validations such as validates_uniqueness_of are one way in which models can enforce data integrity.
Although Active Record does not provide any tools for working directly with such features, the execute method can be used to execute arbitrary SQL.
It looks like running the SQL command yourself with the ActiveRecord execute method may be the best way to go if you really want to enforce uniqueness in the database.
Solution 2
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
Misha Moroshko
I build products that make humans happier. Previously Front End engineer at Facebook. Now, reimagining live experiences at https://muso.live
Updated on June 03, 2022Comments
-
Misha Moroshko almost 2 years
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 ?