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?
You can add a validation to your model to forbid duplicated values
class MyModel < ActiveRecord::Base
validates_uniqueness_of :my_column_name
end
counter = 0
Model.all.each {|m| m.some_value = counter; m.save; counter += 1;}
:)
and then add validation as @j. answered
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
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