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?
Previous answers use find or last require the creation of ActiveModel, which take extra computation time.
find
last
I think using pluck is better, since it only creates an Array of ids.
pluck
ids = Foo.limit(n).order('id DESC').pluck(:id) Foo.where('id NOT IN (?)', ids).destroy_all