Skip to content

Instantly share code, notes, and snippets.

@attilagyorffy
Last active July 25, 2016 21:15
Show Gist options
  • Save attilagyorffy/8380ae76bd6decde46336d658d82dc41 to your computer and use it in GitHub Desktop.
Save attilagyorffy/8380ae76bd6decde46336d658d82dc41 to your computer and use it in GitHub Desktop.
Avoiding PG::NotNullViolation errors when adding new columns
class AddFirstAndLastNameToUsers < ActiveRecord::Migration
def change
add_column :users, :first_name, :string, null: false
add_column :users, :last_name, :string, null: false
end
end
class AddFirstAndLastNameToUsers < ActiveRecord::Migration
def up
add_column :users, :first_name, :string
add_column :users, :last_name, :string
execute <<-SQL.strip_heredoc
UPDATE users
SET first_name = '[[UPDATEME]]'
WHERE first_name IS NULL
SQL
execute <<-SQL.strip_heredoc
UPDATE users
SET last_name = '[[UPDATEME]]'
WHERE last_name IS NULL
SQL
change_column :users, :first_name, :string, null: false
change_column :users, :last_name, :string, null: false
end
def down
remove_column :users, :first_name
remove_column :users, :last_name
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment