Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change multiple columns with one single migration change

I have the following migration. Is there a way to run these changes in one change than 3?

def change
 change_column :comments, :attr_1, :string, null: true
 change_column :comments, :attr_2, :string, null: true
 change_column :comments, :attr_3, :string, null: true
end
like image 724
mikeymurph77 Avatar asked Nov 02 '25 00:11

mikeymurph77


1 Answers

The short answer is no. The change_column method is configured to take arguments for table name, column name, and an options hash. The source code for change_column can be found here: https://github.com/rails/rails/blob/0fe76197d2622674e1796a9a000995a7a1f6622b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb

The only line in the change_column method is: execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_sql(table_name, column_name, type, options)}")

which executes an ALTER script on the table name passed as the first argument. You can't pass an array of tables/columns as arguments, so you have to do them one at a time. This paradigm is fairly typical in Rails migrations.

like image 164
NM Pennypacker Avatar answered Nov 03 '25 17:11

NM Pennypacker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!