Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add unique to a table column in ruby on rails

I have a table with some columns, now i need to modify one column to make it unique(no duplicate values), how can i do that in ruby on rails?

like image 926
ohana Avatar asked May 13 '10 20:05

ohana


People also ask

What is a unique index?

Unique indexes are indexes that help maintain data integrity by ensuring that no rows of data in a table have identical key values. When you create a unique index for an existing table with data, values in the columns or expressions that comprise the index key are checked for uniqueness.

What is unique index in Postgres?

PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.

What is a migration in Ruby?

Migrations are a convenient way to alter your database schema over time in a consistent way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent. You can think of each migration as being a new 'version' of the database.


1 Answers

You can add a validation to your model to forbid duplicated values

class MyModel < ActiveRecord::Base
   validates_uniqueness_of :my_column_name
end
like image 55
Ju Nogueira Avatar answered Nov 07 '22 02:11

Ju Nogueira