stevec
stevec

Reputation: 52268

Remove all records from a certain id onwards in rails?

I accidentally forgot to turn a scheduled task and added rows to a table that shouldn't be there.

I know the id from which I wish to remove rows. But how do you do it?

I've tried

Datum.where("id > 650").delete
ArgumentError (wrong number of arguments (given 0, expected 1))

also

Datum.where("id > 650").destroy
Traceback (most recent call last):
        1: from (irb):5
ArgumentError (wrong number of arguments (given 0, expected 1))

Upvotes: 0

Views: 1250

Answers (2)

Tobias Münch
Tobias Münch

Reputation: 859

first of all delete_all vs destroy_all in a short comparison:

  • delete_all: Will delete your data directly from the table without instantiating your ActiveRecord; Faster, but maybe not save depended on your model.
  • destroy_all: Your ActiveRecord will be instantiating and your Callbacks, Cascade Deletes and so on will be performed. Slower, but save.

If you have a RecordSet you always have to perfrom delete/destroy_all because the methods delete/destroy are only for a single ActiveRecord.

Sources:

Upvotes: 4

stevec
stevec

Reputation: 52268

Seems to be with destroy_all

Datum.where("id > 650").destroy_all
  Datum Load (0.4ms)  SELECT "data".* FROM "data" WHERE (id > 650)
   (0.1ms)  BEGIN
  Datum Destroy (10.2ms)  DELETE FROM "data" WHERE "data"."id" = $1  [["id", 651]]
   (0.5ms)  COMMIT
   (0.1ms)  BEGIN
  Datum Destroy (0.3ms)  DELETE FROM "data" WHERE "data"."id" = $1  [["id", 652]]
   (0.3ms)  COMMIT
   (0.1ms)  BEGIN
  Datum Destroy (0.3ms)  DELETE FROM "data" WHERE "data"."id" = $1  [["id", 653]]
   (0.2ms)  COMMIT

I suspect destroy doesn't work because it protecting against the small chance of a disaster when someone meant to delete one record but accidentally provided multiple

Upvotes: 0

Related Questions