Rails destroy all but newest n records

后端 未结 7 926
眼角桃花
眼角桃花 2021-02-18 17:00

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条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-18 17:47

    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)
    

提交回复
热议问题