How to add default value for column added by rails g migration command

I know how to add a default value in an already created migration file. i.e.,

`rails generate migration AddTestColumnToTesttable test_status:boolean` to create it. 

It will generate this migration:

 class AddTestColumnToTable < ActiveRecord::Migration def change add_column :table, :test_status, :boolean, :default => true end end 

But can we add a default value through the rails g migration command?

+10
source share
2 answers

No , this cannot be done from the command line, you need to change this in the migration file

 add_column :table, :test_status, :boolean, :default => true 

Hope this helps!

+14
source

** Rails 4.X + **

Now, since it is not possible to add a new column to the table with the default value defined by the terminal in the rail migration, the following steps must be taken to add a new column to the existing table with the default value true or false.

1. Run the migration from the command line to add a new column

 $ rails generate migration add_columnname_to_tablename columnname:boolean 

The above command will add a new column to your table.

2. Set the new column value to TRUE / FALSE by editing the new migration file.

 class AddColumnnameToTablename < ActiveRecord::Migration def change add_column :tablename, :columnname, :boolean, default: false end end 

** 3. To make changes to the application database table, run the following command in the terminal **

 $ rake db:migrate 
+5
source

All Articles