Last active
April 27, 2016 21:01
-
-
Save withhawaii/37dbe48687229458eaabb7a124f740c5 to your computer and use it in GitHub Desktop.
Sometime you may need to modify multiple table columns in a migration. Here is my best practice when you need to update multiple table columns in a migration.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#The example below will easily get screwed up when your statements fails in the middle of migrations, i.e., fail after the line 9. | |
#It will require manual fix to recover your table to healthy state. | |
#MySQL support does not support rollbacking DDL statements (Postgres does it though). | |
class UpdateUsers < ActiveRecord::Migration | |
def change | |
add_column(:users, :type, :string) | |
remove_column(:users, :first_name) | |
remove_column(:users, :last_name) | |
rename_column(:users, :dob, :birth_date) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#The better approach is using change_table command and turn :bulk option to true. | |
#With bulk option, change_table will generate a single ALTER TABLE statement, | |
#which is much faster and this migration will fail UNLESS all modification are successful. | |
#More information, please check the api at http://apidock.com/rails/ActiveRecord/ConnectionAdapters/Table | |
class UpdateUsers < ActiveRecord::Migration | |
def change | |
change_table :users, :bulk => true do |t| | |
t.column :type, :string | |
t.remove :first_name | |
t.remove :last_name | |
t.rename :dob, :birth_date | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment