Rails destroy all but newest n records

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

    Previous answers use find or last require the creation of ActiveModel, which take extra computation time.

    I think using pluck is better, since it only creates an Array of ids.

    ids = Foo.limit(n).order('id DESC').pluck(:id)
    Foo.where('id NOT IN (?)', ids).destroy_all
    

提交回复
热议问题