'change default value to a column through a migration

I have an existing table in which default value of column is already set. This table contains lot of data in it. I don't want to change any of exiting record in table(don't want to change column of exiting record), but from here onwards I want to change the default value of that column. How do I do that?

Rails version: Rails 4.0.13 Ruby version: ruby 2.2.10p489



Solution 1:[1]

Consider I want to change default value of a field(is_male) in table(users). My users table contains lot of data in it where I want to change the default value of is_male column which is of type tinyint, from true to false.

I have created a migration using:

rails g migration add_default_false_to_is_male_for_users

made below changes in migration file:

class AddDefaultFalseToColumnNameTableName < ActiveRecord::Migration
  def up
    change_column_default :users, :is_male, false
  end
    
  def down
    change_column_default :users, :is_male, true
  end
end

It won't change existing data.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shailjakant