add column with default value in rails

To add a column with a default value in Ruby on Rails, follow these steps:

  1. Open the migration file: Open the migration file for the relevant table. Migration files are located in the db/migrate directory of your Rails application. Look for a file with a name like YYYYMMDDHHMMSS_create_table_name.rb, where YYYYMMDDHHMMSS represents the timestamp of the migration creation.

  2. Add the column: Inside the migration file, use the add_column method to add the new column. Provide the table name as the first argument, followed by the column name and its data type. For example, if you want to add a column named new_column with a string data type to the table_name table, the code would look like this: add_column :table_name, :new_column, :string.

  3. Specify the default value: To set a default value for the column, add the default option to the add_column method. This option takes the desired default value as an argument. For example, if you want the default value of the new_column to be 'default_value', you can modify the previous code like this: add_column :table_name, :new_column, :string, default: 'default_value'.

  4. Save and run the migration: Save the migration file and run the migration command to apply the changes to the database. In your terminal, navigate to the root directory of your Rails application and run the following command: rails db:migrate.

  5. Verify the column: Once the migration is completed successfully, you can verify the addition of the new column with the default value by checking the database schema or using a database management tool.

That's it! You have successfully added a column with a default value in Ruby on Rails. Remember to adjust the table name, column name, data type, and default value according to your specific requirements.