add column with default value in rails
To add a column with a default value in Ruby on Rails, follow these steps:
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 likeYYYYMMDDHHMMSS_create_table_name.rb
, whereYYYYMMDDHHMMSS
represents the timestamp of the migration creation.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 namednew_column
with a string data type to thetable_name
table, the code would look like this:add_column :table_name, :new_column, :string
.Specify the default value: To set a default value for the column, add the
default
option to theadd_column
method. This option takes the desired default value as an argument. For example, if you want the default value of thenew_column
to be'default_value'
, you can modify the previous code like this:add_column :table_name, :new_column, :string, default: 'default_value'
.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
.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.