ohana
ohana

Reputation: 179

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?

Upvotes: 8

Views: 5851

Answers (5)

taimur akhtar
taimur akhtar

Reputation: 151

class MyModel < ActiveRecord::Base
  validates_uniqueness_of :my_column_name
end

suggested above may break, if you’re running Unicorn on multiple Heroku dynos, each with multiple web processes etc.

so a better way to do it would be

class AddEmailIndexToUser
  def change
    # If you already have non-unique index on email, you will need
    # to remove it before you're able to add the unique index.
    add_index :users, :email, unique: true
  end
end

https://robots.thoughtbot.com/the-perils-of-uniqueness-validations

or you can use raw sql in migration to do this.

execute <<-SQL
  ALTER TABLE Persons
  ADD UNIQUE (P_Id)
SQL

Upvotes: 4

Schneems
Schneems

Reputation: 15828

This is code directly from my working project:

add_index( :tickets, [:to_email, :body_hash, :from_email] , :unique => true, :limit => 255)

Note the limit functionality is only required if you are using unique on a text field (rather than string) though it isn't implemented in rails yet (coming in 3.0 i believe). You can get around this limitation by using the mysql_index_length plugin http://github.com/eparreno/mysql_index_length/

add_index( :table_name, [:column_name, :second_column_name, :third_column_name] , :unique => true, :limit => 255)

this example is creating a unique index for three columns though you can use it for one column if you desire.

Link to the project on GitHub: http://github.com/thinkbohemian/WhySpam/blob/master/db/migrate/20091223193335_add_unique_index.rb

Upvotes: 3

tybro0103
tybro0103

Reputation: 49693

Someone correct me if I'm wrong because I haven't used this personally, but I believe you can use a migration to set uniqueness on the database level.

def self.up
    change_column :<table name>, :<attribute name>, :<data type>, :unique => true
end

Upvotes: -1

klew
klew

Reputation: 14967

 counter = 0
 Model.all.each {|m| m.some_value = counter; m.save; counter += 1;}

:)

and then add validation as @j. answered

Upvotes: -4

Ju Nogueira
Ju Nogueira

Reputation: 8461

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

class MyModel < ActiveRecord::Base
   validates_uniqueness_of :my_column_name
end

Upvotes: 7

Related Questions