Change the default value for table column with migration Change the default value for table column with migration ruby ruby

Change the default value for table column with migration


It is strange, because according to documentation (change_column_default) your code should work..

As an option you might define up and down:

class ChangeDefaultvalueForHideSeasonSelector < ActiveRecord::Migration  def up    change_column_default :plussites, :hide_season_selector, true  end  def down    change_column_default :plussites, :hide_season_selector, false  endend


You have to check which version of ActiveRecord you are using. According to you command rake db:migrate you are still on rails 4.2 or earlier.

If you are on ActiveRecord up to 4.2 (change_column_default 4.2.9), there is no from/to option and you can define only the new default option as param.

class ChangeDefaultvalueForHideSeasonSelector < ActiveRecord::Migration   def change     change_column_default :plussites, :hide_season_selector, true   endend

The solution above won't allow a rollback as the method don't know, what the previous default value was. This is why you have to define an separate up and down method:

class ChangeDefaultvalueForHideSeasonSelector < ActiveRecord::Migration  def up    change_column_default :plussites, :hide_season_selector, true  end  def down    change_column_default :plussites, :hide_season_selector, false  endend

If you are on rails 5 or newer, there are new possibilities to define the value which was before and which one should be after by from/to (change_column_default 5.0.0.1). On rails 5 you ca use your chosen solution:

class ChangeDefaultvalueForHideSeasonSelector < ActiveRecord::Migration   def change     change_column_default :plussites, :hide_season_selector, from: false, to: true   endend

I hope this explanation will help the people with comments under the other answer.