You can use change() method: Schema::table('users', function ($table) { $table->integer('active')->default(0)->change(); }); Then run migrate command.
Deploy and update the column in a rake task or on the console while your app is running. Make sure your application already writes data to that colum for new/updated rows. Add another change_column migration, which then changes the default of that column to the desired default value.
To set a default value for a column, specify the DEFAULT clause in the CREATE TABLE statement. For details about the DEFAULT clause, see DEFAULT clause in the manual HADB SQL Reference . If the DEFAULT clause is omitted, the default value for the column will be the null value.
Here's how you should do it:
change_column :users, :admin, :boolean, :default => false
But some databases, like PostgreSQL, will not update the field for rows previously created, so make sure you update the field manaully on the migration too.
change_column_default :employees, :foreign, false
For Rails 4+, use change_column_default
def change
change_column_default :table, :column, value
end
Using def change
means you should write migrations that are reversible. And change_column
is not reversible. You can go up but you cannot go down, since change_column
is irreversible.
Instead, though it may be a couple extra lines, you should use def up
and def down
So if you have a column with no default value, then you should do this to add a default value.
def up
change_column :users, :admin, :boolean, default: false
end
def down
change_column :users, :admin, :boolean, default: nil
end
Or if you want to change the default value for an existing column.
def up
change_column :users, :admin, :boolean, default: false
end
def down
change_column :users, :admin, :boolean, default: true
end
As of Rails 4 you can't generate a migration to add a column to a table with a default value, The following steps add a new column to an existing table with default value true or false.
$ rails generate migration add_columnname_to_tablename columnname:boolean
The above command will add a new column in your table.
class AddColumnnameToTablename < ActiveRecord::Migration
def change
add_column :table_name, :column_name, :boolean, default: false
end
end
$ rake db:migrate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With