Rails 4: Remove not null constraint from table column with migration?
Given the following schema.rb
:
create_table "people", force: true do |t|
t.string "name", null: false
t.integer "age"
t.integer "height"
t.string "email"
t.boolean "married", default: false
t.text "bio"
t.integer "fav_number"
t.decimal "lucky_num", precision: 2, scale: 2
t.datetime "birthday"
t.datetime "created_at"
t.datetime "updated_at"
end
I'd like to remove the name
default value of null: false
. I've tried running a separate migration with change_column_default
, but that had no impact on schema.rb
. Any suggestions?
Solution 1:
From the docs:
def up
change_column_default :table_name, :status, 0
end
def down
change_column_default :table_name, :status, nil
end
Solution 2:
The 'up' function will definitely do the job when you do db:migrate.
But in the future, in some cases, like rollback, you might want a function to reverse this particular migration.
def up
change_column_null :people, :name, true
end
def down
change_column_null :people, :name, false
end
Solution 3:
It sounds like you're not trying to change the default value of the column, but rather to remove the NOT NULL constraint and allow null values (i.e. change from "null: false" to the default "null: true"). If that's the case, then you can use change_column_null:
class ChangeNameNull < ActiveRecord::Migration
def change
change_column_null :people, :name, true
end
end
Edit 1:- Fixed typo