Categories
Rails

Ruby On Rails: manually generating a migration. Enforce uniqueness of a database column

$ rails generate migration add_email_uniqueness_index

It will create the following file:
db/migrate/_add_email_uniqueness_index.rb

In this case, we are adding an index to the email address column, to guarantee its uniqueness, so the file will look like this:

class AddEmailUniquenessIndex < ActiveRecord::Migration
def self.up
add_index :users, :email, :unique => true
end
def self.down
remove_index :users, :email
end
end

Now that we are in the subject of uniqueness, even as we are enforcing it by adding the :unique => true directly as a db constrain, we should in fact enforce this in the model level instead. By adding the following lines:

validates_uniqueness_of :my_column_name

If you do that on your model, you get the benefits of validation, instead of a db error you would have to handle

Another example:
$ rails generate migration add_password_to_users encrypted_password:string
By adding “_to_users” we are indicating rails what table we want this added to, the generated code looks as below:
class AddPasswordToUsers < ActiveRecord::Migration
def self.up
add_column :users, :encrypted_password, :string
end
def self.down
remove_column :users, :encrypted_password
end
end

RAILS 4 UPDATE: instead of self.up and self.down, we have the word “change” now

Leave a Reply

Your email address will not be published. Required fields are marked *