Rails destroy all but newest n records

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

    [Rails 5 / ActiveRecord::Relation]

    destroy_all no longer takes parameters... Actually, the ActiveRecord::Relation never allowed parameters I don't think... Anyway, you should just put the condition before it, but use destroy_all after the query, like this:

    Person.destroy_all("last_login < '2004-04-04'")
    Person.destroy_all(status: "inactive")
    Person.where(age: 0..18).destroy_all
    

提交回复
热议问题