ActiveRecord - Get the last n records and delete them in one command?

rails-activerecord, ruby

Solution

To do it in one SQL query use `delete_all`:

Model.order(created_at: :desc).limit(n).delete_all

But `delete_all` won't execute any model callbacks or validations

To run callbacks and validations use `destroy_all`:

Model.order(created_at: :desc).limit(n).destroy_all

Unfortunately `destroy_all` will execute n + 1 SQL queries: 1 query to retrieve records and n queries to delete each record.

Problem

Hello all and thanks for taking the time to answer my question. The question is really explained in the title. I tried Model.last(n).destroy_all but none of that would work. I was wondering if it is possible to do it in one line, and if not what would be the cleanest way of doing it? Thanks again!

Original source