Ruby on Rails: ¿Cómo agrego una restricción not null a una columna existente usando una migración?


En mi aplicación Rails (3.2), tengo un montón de tablas en mi base de datos, pero olvidé agregar algunas restricciones no nulas. He buscado en Google, pero no puedo encontrar cómo escribir una migración que agrega not null a una columna existente.

TIA.

Author: David Robertson, 2012-02-15

4 answers

Intenta change_column :

change_column :table_name, :column_name, :column_type, null: false
 85
Author: Dan Wich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-08 12:18:36

También puedes usar change_column_null :

change_column_null :table_name, :column_name, false
 219
Author: nates,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-28 00:24:16

1) PRIMERO: Agregue la columna con el valor predeterminado

2) ENTONCES: Eliminar el valor predeterminado

add_column :orders, :items, :integer, null: false, default: 0
change_column :orders, :items, :integer, default: nil
 7
Author: rndrfero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-06 14:03:14

Si lo está utilizando en un nuevo script/esquema de migración create, aquí es cómo podemos definirlo

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
 1
Author: Manjunath Reddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-30 15:50:00