Rails destroy all but newest n records

Viewed 14147

How do I destroy all but the newest n records using Rails' ActiveRecord?

I can get the newest n records using order and limit but how do I destroy the inverse?

7 Answers

None of these work in Rails 6, but delete_by does.

keep_ids = [2345, 345256, 34]
Component.delete_by('id NOT IN (?) AND status = "inactive"', keep_ids) }
Related