Rails destroy all but newest n records

后端 未结 7 922
眼角桃花
眼角桃花 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:36

    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.

提交回复
热议问题