Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Migration in Rails - Part2

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.17k
    Comment on it

    Hi friends,

    In my last blog  Migrations in Rails: PART 1 - Introduction and Creating Tables I told you what is migration and how we can create tables in migration today I will tell you some other generic queries that are used:

    1. Dropping a table:

    To drop a table you need to create migrations like:

    rails g migration dropArticleTable
    #=> 
        invoke  active_record
        create  db/migrate/20160517170025_drop_article_table.rb

     

    Now inside 20160517170025_drop_article_table.rb write this code

        class DropArticleTable < ActiveRecord::Migration
          def change
            drop_table :articles 
          end
          #articles is the name of the table to be dropped
        end

     

    2. Adding a column to a table:

    For adding a column to a table you can create migration directly using generator. Suppose you want to add column profile_pic of string type to users table then you can generate it by

    rails g migration addProfilePicToUsers profile_pic:string
    

     

    It will automatically create migration file like:

        class AddProfilePicToUsers < ActiveRecord::Migration
          def change
            add_column :users, :profile_pic, :string
          end
        end

     

    So for adding columns to a table in the end of the migration name you need to specify "ToTableName" and after that column name with their types. It will automatically create migration. You can also edit the migration file before running if you want to add some more thing to this migration

     

    3. Removing a column from a table:

    Similarly for removing a column from a table you need to run the migration like:

    rails g migration removeProfilePicFromUsers profile_pic:string

     

    It will automatically create migration file like:

        class RemoveProfilePicFromUsers < ActiveRecord::Migration
          def change
            remove_column :users, :profile_pic, :string
          end
        end

     

    Here the default suffix for removing the column is "FromTable" with column names and its type as given in the example above.

     

    Hope you liked this blog.

 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: