views:

26

answers:

2

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?

A: 

Person.destroy_all("last_login < '2004-04-04'") will destroy all persons who meet the condition. So all you need is inverted conditions and destroy_all

Tadas Tamosauskas
A: 

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)
vonconrad