ActiveRecord slow_delete_all

Deletes taking to long, just take a break ๐Ÿ™‚
(so replication can catch up/things get unblocked)

Only use save sql, there is no escapeing.

  class ActiveRecord::Base
    def self.slow_delete_all(condition)
      count = 0
      loop do
        result = ActiveRecord::Base.connection.send(:delete_sql, "delete from #{table_name} where #{condition} limit 10000")
        count += result
        break if result == 0
        sleep 1
      end
      count
    end
  end

Convertig a HABTM join table to a real activerecord model

If your has_and_belongs_to_many associations suddenly need to know more, its time to convert them to a real model.

  • rename table
  • add id
  • add created_at/updated_at as not-null (need to set existing records to something)

Code

class CreateJoinModel < ActiveRecord::Migration
  def change
    rename_table :products_users, :purchases
    add_column :purchases, :id, :primary_key
    [:created_at, :updated_at].each do |column|
      add_column :purchases, column, :timestamp, null: false, default: Time.at(0)
      change_column_default :purchases, column, nil
    end
  end
end