简体   繁体   中英

More efficient way of doing destroy_all in Rails?

Is there a quicker way of doing destroy all in rails?

I'm asking this because rails does an individual delete sql query per record.

For example calling destroy all on a search for 4 records would then run 4 delete sql commands.

Blerg.where("created_at > yesterday").destroy_all (4 results)

then calles…

DELETE FROM "blergs" WHERE "blergs"."id" = $1  [["id", 197782]]

4 times.

Is there a way to get it into one sql command?

You can allways call

Blerg.where("created_at > yesterday").delete_all

This gives only one query:

DELETE FROM "blergs" WHERE (created_at > '2012-11-26 16:27:56.678872')

Note that this does not call any callbacks on the objects which are to be deleted.

You can also do

Blerg.delete_all("created_at > '2012-11-01 00:00:00'")

which is more succinct. It executes one SQL statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM