Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record: delete_all with limit

Trying to get a definitive answer on whether it's possible to limit a delete_all to X number of records.

I'm trying the following:

Model.where(:account_id => account).order(:id).limit(1000).delete_all

but it doesn't seem to respect the limit and instead just deletes all Model where :account_id => account.

I would expect it to generate the following:

delete from model where account_id = ? order by id limit 1000

This seems to work fine when using destroy_all but I want to delete in bulk.

like image 907
Bradley Avatar asked Nov 18 '11 01:11

Bradley


People also ask

What is active record used for?

Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

What is Active Record Ruby?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

How do I delete a record in Ruby on Rails?

By using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.


1 Answers

This one also worked pretty well to me (and my needs)

Model.connection.exec_delete('DELETE FROM models ORDER BY id LIMIT 10000', 'DELETE', [])

I know it might seem a bit cumbersome but it'll return the affected rows AND also will log the query through the rails logger. ;)

like image 114
leandroico Avatar answered Sep 28 '22 15:09

leandroico