Run SQL updates in Rails migration
An approach to running rails migration sql code after adding a column
The proper way to run Ruby migrations is with the change
definition. This allows rollbacks to remove any column or change that is run inside that block and reduces the need to have an up
and down
method to reverse the changes. But, sometimes you need to run some updates on a new table or column that is added to the database. In order, to do this you have to only run that sql on the up
state when the column exists.
Example:
class AddCountToThingsTable < ActiveRecord::Migration
def change
change_table :things do |t|
t.integer :items_count, default: 0
end
reversible do |dir|
dir.up { data }
end
end
def data
execute <<-SQL.squish
UPDATE things
SET items_count = (SELECT count(1)
FROM items
WHERE items.thing_id = things.id)
SQL
end
end
In the above example, the reversible block is used within change to run a reversible
change to the database. The up is provided a closure which will run the data method to update the column that is added. This will not be run with down, since there was no closure provided with it.
Hope this helps, let me know some other techniques you can think of.