Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 976
gabethegrape Avatar asked Apr 16 '14 02:04

gabethegrape


People also ask

How to make a column NOT NULL in rails?

Before you are making a column NOT NULL you would want to make user there are no cells that are null or you risk running in to an exception. You can do this by providing a default value or manually setting the value using a loop. or you can add a default value to the change_column_null method.

What is null false in rails migration?

According to the documentation one of these options is :null which allows or disallows NULL values in the column. So, in summary :null => false would mean "Do not allow NULL values in the new or update column".

How do I rollback migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.

Can foreign key be null rails?

add_foreign_key simply adds a foreign key constraint whether the field is required or not (in your case author_id in articles ). Did you get an error when you tried this in your migration? SO, if in your original migration of articles , author_id is null, then you can have foreign key that's nullable.


1 Answers

From the docs:

  def up     change_column_default :table_name, :status, 0   end    def down     change_column_default :table_name, :status, nil   end 
like image 126
luigi7up Avatar answered Sep 22 '22 14:09

luigi7up