Ruby on Rails: How do I add a not null constraint to an existing column using a migration?

…衆ロ難τιáo~ 提交于 2019-12-03 03:21:53

问题


In my Rails (3.2) app, I have a bunch of tables in my database but I forgot to add a few not null constraints. I've googled around but I can't find how to write a migration which adds not null to an existing column.

TIA.


回答1:


For Rails 4+, nates' answer (using change_column_null) is better.

Pre-Rails 4, try change_column.




回答2:


You can also use change_column_null:

change_column_null :table_name, :column_name, false



回答3:


1) FIRST: Add column with default value

2) THEN: Remove default value

add_column :orders, :items, :integer, null: false, default: 0
change_column :orders, :items, :integer, default: nil



回答4:


If you are using it on a new create migration script/schema here is how we can define it

class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
    t.string :name, null: false     # Notice here, NOT NULL definition
    t.string :email, null: false
    t.string :password, null: false
    t.integer :created_by
    t.integer :updated_by 

    t.datetime :created_at
    t.datetime :updated_at, default: -> { 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP' }
   end
  end
end


来源:https://stackoverflow.com/questions/9286176/ruby-on-rails-how-do-i-add-a-not-null-constraint-to-an-existing-column-using-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!