ruby-on-railscallbackdatabase-migrationrails-migrations

Rails - shall I set_callbacks after skip_callbacks?


In a migration I disable callbacks like:

class AlignUserAreaToCountry < ActiveRecord::Migration
  def up
    # disable the after_initialize :_set_defaults callback
    User.skip_callback(:initialize, :after, :_set_defaults)
    ...
  end
end

Shall I call User.set_callback(...) at the end of the same up method?


Solution

  • Last time I remember, you do need to re-enable the callbacks with set_callback. Thankfully, you can pass a block to skip_callback and run your migration so you don't need to do explicitly:

    User.skip_callback(:initialize, :after, :_set_defaults) do 
      add_column :users, :first_name, :string
    end
    

    More info in ActiveSupport::Callbacks::ClassMethods, http://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html

    However, this solution is not thread-safe. I would recommend using a virtual attribute (such as dont_apply_callbacks) and if its presence exists, skip the desired callbacks.