Rails Migration: Remove constraint

Ruby on-RailsDatabase Migration

Ruby on-Rails Problem Overview


I have a table in a Rails application which (in schema.rb) looks like:

create_table "users", :force => true do |t|
   t.string "name", :null=>false
   t.string "address", :null=>false
end

I would like to write a rails migration to allow nulls for the address field. i.e. after the migration the table looks like this:

create_table "users", :force => true do |t|
   t.string "name", :null=>false
   t.string "address"
end

What do I need to do to remove the constraint?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

In Rails 4+ in order to remove not-null constraint, you can use change_column_null:

change_column_null :users, :address, true

Solution 2 - Ruby on-Rails

Not sure you can call t.address? Anyway... I would use change_column like so

change_column :users, :address, :string, :null => true

Docs... http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_column

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJay GodseView Question on Stackoverflow
Solution 1 - Ruby on-RailsdeepakView Answer on Stackoverflow
Solution 2 - Ruby on-RailsPaul SturgessView Answer on Stackoverflow