Keith Schacht’s Weblog

Subscribe

💡 TIL: Rails migrations can include an up_only part

29th October 2024

When writing a migration in Rails and you need to do one thing which can’t be automatically reversed, I always convert a def change to up and down. It turns out you can slip in an up_only block:

class AddFieldsToUsers < ActiveRecord::Migration[7.1]
  def change
    add_column :users, :first_name, :string
    add_column :users, :last_name, :string

    up_only do
      User.delete_all
    end
  end
end
from RubyCademy

This is Rails migrations can include an up_only part by Keith Schacht, posted on 29th October 2024.

Part of series Today I Learned

  1. Ruby can chain methods and right-assign - Oct. 29, 2024, 8:23 p.m.
  2. Rails migrations can include an up_only part - Oct. 29, 2024, 8:29 p.m.
  3. NASA's Dragonfly probe to Saturn's Titan in 2028 - Nov. 26, 2024, 2:58 p.m.
  4. Rails ActiveRecord has a .sole method - Nov. 26, 2024, 11:15 p.m.
  5. pick is the single-value version of pluck in Rails - Nov. 26, 2024, 11:24 p.m.

Next: Ruby Sorbet is too verbose, can the syntax be improved?

Previous: Ruby can chain methods and right-assign