Is there a way, using rake, to delete all but the last 30 or so results from the database? Would I have to get the database count, check the result from 30 back and then delete all with a creation date before it?
Sure, just do it as you suggested:
delete_all_but_oldest_30.rake:
task :delete_all_but_oldest_30 => :environment do
query = MyModel.order("created_at desc")
query.limit(query.count - 30).destroy_all
end
You should customize this as you see fit-- you just need to decide what 'last' means: oldest, highest ID, lowest ID, etc. Just use the reverse of whatever order you'd like so that the last 30 results are those that you'd like to keep. So to keep the lowest IDs, order by "id desc"
.
Note: This technically doesn't guarantee that exactly 30 records are left because it is non-transactional. When more records are added asynchronously while this rake task is running, the result is not deterministic. Depending on your application, this may or may not be a problem. If you're just deleting old records, I suspect this rake task is fine. If not, you could wrap the entire task in a transaction
. However, that is inadvisable if you're deleting a large number of records as the transaction will tie up the database.