Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails destroy all but newest n records

Tags:

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?

like image 830
dteoh Avatar asked Oct 16 '10 08:10

dteoh


2 Answers

Either of these methods would do it:

# Fetch your latest N records
newest_n_records = Foo.find(:all, :order => 'created_at DESC', :limit => n)

# Then do:
Foo.destroy_all(['id NOT IN (?)', newest_n_records.collect(&:id)])

# Or:
Foo.destroy_all('created_at < ?', newest_n_records.last.created_at)
like image 88
vonconrad Avatar answered Sep 21 '22 01:09

vonconrad


I have two methods of doing this, assuming n = 5:

Foo.order('id desc').offset(5).destroy_all

This sorts records with latest first, and destroys everything past the 5th records. Or

Foo.destroy_all(['id <= ?', Foo.order('id desc').limit(1).offset(5).first.id])

This finds the 6th latest record id and deletes all records with id <= 6th latest record id.

Also, you might want to look at this SO question.

like image 40
konyak Avatar answered Sep 22 '22 01:09

konyak