Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Adding a default value for a column through migration

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 182
    Comment on it

    Consider the following scenario.

    Let us say we have a User model and users ,its corresponding table in the database has a column role_id along with other columns.

    During the time of the attachment of the role_id to users table ,we could have written the following migration so that it receives a default value :

    class AddRoleIdToUsers < ActiveRecord::Migration
      def change
    
        add_column :users, :role_id, :integer,:default => 2
    
        add_index :users, :role_id
    
      end
    
    end
    

    An index has been there for a faster search.

    Now if we added the column but  accidently or unknowingly forgot to add default option ,we can do something like this.

    generate an empty migartion using rails g migration GiveDefaultValueForRoleId and modify the change method as described below:

    class GiveDefautvalueForRoleId < ActiveRecord::Migration
    
       def change
    
       change_column :users ,:role_id ,:integer ,default: 2
    
    
      end
    end

    here the name of the migration is of no importance but it should produce some sense.

    The change_column method here takes table name,column name,column 's data type and a hash

    as its parameters in the same order.

    But a caution here ,it won't provide default values for the earilier created records so we have to manually update them using rails console.

    Thank you

 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: