Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Last active December 17, 2017 10:47
Show Gist options
  • Save StevenJL/56c69ad3068a1061de3430e94ba58d84 to your computer and use it in GitHub Desktop.
Save StevenJL/56c69ad3068a1061de3430e94ba58d84 to your computer and use it in GitHub Desktop.
# Deleting a large amount of records by invoking `destroy` on
# each record results in a single query per record.
deadbeat_users = User.where(payment_status: "deadbeat")
deadbeat_users.each do |deadbeat|
deadbeat.destroy
end
# DELETE FROM users WHERE id = 13;
# DELETE FROM users WHERE id = 42;
# DELETE FROM users WHERE id = 49;
# DELETE FROM users WHERE id = 420;
# DELETE FROM users WHERE id = 666;
# ...
# Use `delete_all` to batch delete these records with one query,
# if we do not need `after_destroy` callbacks to be invoked. Note
# AR callbacks are pretty much an antipattern these days.
deadbeat_users.delete_all
# DELETE FROM users WHERE users.status = 'deadbeat';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment