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
add_column :users, :is_admin, :string, :default => "false"
- 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
change_column :employees , :article_subscription , :string ,default: "false"
So hope this article was helpful to understand how to give default values in rails application by two different ways.