views:

92

answers:

4

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

+2  A: 

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

class MyModel < ActiveRecord::Base
   validates_uniqueness_of :my_column_name
end
j.
this won't work at the mysql table level...
ohana
A: 
 counter = 0
 Model.all.each {|m| m.some_value = counter; m.save; counter += 1;}

:)

and then add validation as @j. answered

klew
A: 

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
tybro0103
tried this one, didn't work.
ohana
what database are you using?
tybro0103
mysql. after i did that, i added duplicate data into the database without a problem
ohana
+1  A: 

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

ThinkBohemian