Friday, April 4, 2014

Add/Rename a column to/in a table in Rails ActiveRecords

Let's consider that you already have a Users table

$ rails generate migration AddEmailToUsers

This will create the following file

db/migrate/some_timestamp_add_email_to_users.rb

Edit this file as the following

class AddEmailToUsers < ActiveRecord::Migration
  def change
    #to add a new column
    add_column :users, :email, :string
    # to rename an existing column
          rename_column :users, :username, :user_name
  end
end

And finally run

rake db:migrate


Check your database, a new column "email" was added to all users tables.


No comments:

Post a Comment