Adding :default => true to boolean in existing Rails column
As a variation on the accepted answer you could also use the change_column_default
method in your migrations:
def up
change_column_default :profiles, :show_attribute, true
end
def down
change_column_default :profiles, :show_attribute, nil
end
Rails API-docs
change_column
is a method of ActiveRecord::Migration
, so you can't call it like that in the console.
If you want to add a default value for this column, create a new migration:
rails g migration add_default_value_to_show_attribute
Then in the migration created:
# That's the more generic way to change a column
def up
change_column :profiles, :show_attribute, :boolean, default: true
end
def down
change_column :profiles, :show_attribute, :boolean, default: nil
end
OR a more specific option:
def up
change_column_default :profiles, :show_attribute, true
end
def down
change_column_default :profiles, :show_attribute, nil
end
Then run rake db:migrate
.
It won't change anything to the already created records. To do that you would have to create a rake task
or just go in the rails console
and update all the records (which I would not recommend in production).
When you added t.boolean :show_attribute, :default => true
to the create_profiles
migration, it's expected that it didn't do anything. Only migrations that have not already been ran are executed. If you started with a fresh database, then it would set the default to true.