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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 112
    Comment on it

    While creating a web application we create models in our application which act as tables in the database. Sometimes when the development of the application moves further, the need arises to add a column to our existing table or removing a column from the table or just changing it. 

    To achieve this, rails active records provide us with migrations with which we can easily do the desired changes in our table. Below are the ways defined to alter our table with the help of migrations.

    • Adding a column

    Let the table be user table and suppose we need to add address column to the table so to add the address column to the user table we need to write this on our console.

    $ rails generate migration add_column_address_to_user address:text

    And after that, we need to run 

    $ rake db:migrate

    so our migration file will look like this

    class AddColumnAddressToUser < ActiveRecord::Migration
      def change
        add_column :users, :address, :text
      end
    end
    • Changing a column

    Suppose now we need to change the data type of address column to string so for that we simply need to write this

    in our migration file

    class ChangeColumnAddressInUser < ActiveRecord::Migration
      def change
        change_column :users, :address, :string
      end
    end

    and then run 

    $ rake db:migrate

     

    • Removing a column

    Now, suppose we need to remove this address column from our users table so for that we will write this on console

    $ rails generate migration remove_column_address_from_user address:string

    and then run

    $ rake db:migrate

    so our migration file will look like this

    class RemoveColumnAddressFromUser < ActiveRecord::Migration
      def change
        remove_column :users, :address, :string
      end
    end

    So these were the three ways through which we can alter our table with the help of active record migrations.

 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: