Execute SQL in Rails migrations
1 min readJul 2, 2019
You may come across the following irreversible Rails migration. It deletes all rows in a table.
class EmptyTable < ActiveRecord::Migration[5.2]
def change
DowJonesExternalData.delete_all
end
end
There is a problem with this migration: At a certain point in time, as soon as the ActiveRecord class DowJonesExternalData
has been deleted, the data migration is going to fail. Other developers will complain, because in their local database the table dow_jones_external_data
still exists and contains data.
Use SQL for data migrations:
class EmptyTable < ActiveRecord::Migration[5.2]
def change
execute 'DELETE FROM dow_jones_external_data'
end
end