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
    • 579
    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 . 

    $ rails generate migration add_column_last_name_to_user last_name:string

    After writing this run the migration command.

    $ rake db:migrate

    The migration file generated will be like :

    class AddColumnLastNameToUser < ActiveRecord::Migration
      def change
        add_column :users, :last_name, :string
      end
    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 :

    class ChangeColumnLastNameInUser < ActiveRecord::Migration
      def change
        change_column :users, :last_name, :text
      end
    end

    After this run the migration command.

    $ rake db:migrate

     

    Removing a Column

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

    $ rails generate migration remove_column_last_name_from_user last_name:text

    After this run the migration command.

    $ rake db:migrate

    Our migration file will be like :

    class RemoveColumnLastNameFromUser < ActiveRecord::Migration
      def change
        remove_column :users, :last_name, :text
      end
    end

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: