Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to add a default value in a column through Migration in rails?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 6.33k
    Comment on it

    As we know that the rails migration is used to interact with the database and create schemas. 

    Many a time when we are creating migrations, we may forget to add a column in the table.

    Or sometimes a need may arise when we have to make some changes in the existing column of the table.

    In these cases, we can alter the migration file of that particular table and do the desired work.

     

    • Adding a column with default value

    Now let's take a situation in which you created a user table but forgot to add a column with some default value.

    So for this what we can do is add a column directly through the migration file like this

    class AddIsAdminToUsers < ActiveRecord::Migration
      
      def change
        add_column :users, :is_admin, :string, :default => "false"
      end
    
    end

     

    • Changing a column to put default value

    Now again let's take a situation in which you created an employee table, along with it, you created a column subscription but forgot to give its default value.

    So for this what we can do is add the default value through the migration file like this.

    class GiveDefautvalueForArticleSubscription < ActiveRecord::Migration
       
      def change
       change_column :employees , :article_subscription , :string ,default: "false"
      end
    
    end

    So hope this article was helpful to understand how to give default values in rails application by two different ways.

 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: