Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Active Records for Adding, Removing or Changing a column

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 658
    Comment on it

    When we create a web application we generally create models which are referred to as tables in the database. Sometimes we need to add a column to the existing table or remove an unused column from the table or just change the column. The way to do all this through migrations are -:

    Adding a Column

    Suppose we have a user table and we need to add a column "last_name" to it . 

    1. $ rails generate migration add_column_last_name_to_user last_name:string

    After writing this run the migration command.

    1. $ rake db:migrate

    The migration file generated will be like :

    1. class AddColumnLastNameToUser < ActiveRecord::Migration
    2. def change
    3. add_column :users, :last_name, :string
    4. end
    5. end

     

    Changing a Column

    If we want to change the datatype of last_name to text , so we need to write the following in our migration file :

    1. class ChangeColumnLastNameInUser < ActiveRecord::Migration
    2. def change
    3. change_column :users, :last_name, :text
    4. end
    5. end

    After this run the migration command.

    1. $ rake db:migrate

     

    Removing a Column

    If we want to remove the last_name column from our user table then we write:

    1. $ rails generate migration remove_column_last_name_from_user last_name:text

    After this run the migration command.

    1. $ rake db:migrate

    Our migration file will be like :

    1. class RemoveColumnLastNameFromUser < ActiveRecord::Migration
    2. def change
    3. remove_column :users, :last_name, :text
    4. end
    5. end

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: