Search code examples
ruby-on-railsrails-activerecordrails-migrations

When using change_column_default on a column with no default, what should be the 'from' value?


This is my create table migration. Please note that I didn't provide the default value for price.

class CreateProducts < ActiveRecord::Migration[5.0]
  def change
    create_table :products do |t|
      t.string :name
      t.decimal :price, precision: 8, scale: 2

      t.timestamps
    end
  end
end

Now I want to set a default value. According to the Migration guide, I should provide from to make it reversible. What value should I provide?

class ChangeProductsPriceDefault < ActiveRecord::Migration[5.0]
  def change
    change_column_default :products, :price, from: 'WHAT_TO_WRITE_HERE?', to: 0
  end
end

Solution

  • "No default" means default is NULL, so:

    change_column_default :products, :price, from: nil, to: 0
    

    There is a description about nil as default: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-change_column_default