导轨摧毁一切,但最新的n条记录 [英] Rails destroy all but newest n records

查看:99
本文介绍了导轨摧毁一切,但最新的n条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何摧毁一切,但使用Rails的ActiveRecord的最新的n条记录?

How do I destroy all but the newest n records using Rails' ActiveRecord?

我可以使用秩序和限制得到最新的N条记录,但我怎么毁灭倒数?

I can get the newest n records using order and limit but how do I destroy the inverse?

推荐答案

这两种方法都将做到这一点:

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)

这篇关于导轨摧毁一切,但最新的n条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆