151

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?

Jay Godse
  • 15,163
  • 16
  • 84
  • 131

2 Answers2

306

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

change_column_null :users, :address, true
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
deepak
  • 7,230
  • 5
  • 24
  • 26
  • Did you actually try this? If you glance at the source code for the function, you see nothing but: `raise NotImplementedError, "change_column_null is not implemented"` – drusepth Oct 23 '14 at 14:32
  • 4
    have used it in postgresql. rails defines it in the database specific adapter see [postgres](http://apidock.com/rails/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter/SchemaStatements/change_column_null), [mysql](http://apidock.com/rails/ActiveRecord/ConnectionAdapters/AbstractMysqlAdapter/change_column_null). can search for others in [apidock](http://apidock.com/rails/search?query=change_column_null). So, will have to check the database adapter for support, in case anyone gets a `NotImplementedError` – deepak Oct 24 '14 at 12:50
  • 3
    Upvote! Here is the link to the [Rails guides](http://edgeguides.rubyonrails.org/active_record_migrations.html#changing-columns) as well. – mcKain Apr 20 '18 at 14:08
  • 1
    This should be the selected answer – nahtnam Aug 09 '19 at 17:50
183

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

Paul Sturgess
  • 3,254
  • 2
  • 23
  • 22