Execute SQL in Rails migrations

Josua Schmid
1 min readJul 2, 2019

--

Use Rails for schema migrations but SQL for data migrations.

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

--

--

Josua Schmid
Josua Schmid

Written by Josua Schmid

I engineer software and craft beer, or the other way around. Find my old blog here: https://web.archive.org/web/20181108025110/http://blog.schmijos.ch/

Responses (1)