[Ruby on Rails] How to Change Default Values of Database Columns
In Ruby on Rails 3.2.3, I changed the default value of a database column, so here’s a memo.
change_column_default(table_name, column_name, default) Sets a new default value for a column.・Source: ActiveRecord::ConnectionAdapters::SchemaStatementsExamples change_column_default(:suppliers, :qualification, ‘new’) change_column_default(:accounts, :authorized, 1) change_column_default(:users, :email, nil)
For example, if you want to change the articles table’s title column definition from “String type, NOT NULL constraint: yes, default value: empty string” to “String type, NOT NULL constraint: no, default value: NULL”, the migration file would be written as follows:
class ChangeTitleNullToArticles < ActiveRecord::Migration
def up
change_column :articles, :title, :string, null: true
change_column_default :articles, :title, nil
end
def down
change_column :articles, :title, :string, null: false
change_column_default :articles, :title, ""
end
end
That’s all from the Gemba.