我创建了一个名为“PostView”的模型。每次用户查看帖子时,都会将其记录到数据库中(使用用户 ID 和帖子 ID 创建一条新记录)。
我只想在数据库中为每个用户保留 10 条记录。因此,每次添加新记录时,我都想删除除最新的 10 条记录之外的所有记录。
- 这有效率吗?如果不是,您建议以什么方式记录用户/帖子视图?
- 如何在 Rails 中添加新记录并删除除最新的 10 条记录之外的所有记录?
谢谢!
我创建了一个名为“PostView”的模型。每次用户查看帖子时,都会将其记录到数据库中(使用用户 ID 和帖子 ID 创建一条新记录)。
我只想在数据库中为每个用户保留 10 条记录。因此,每次添加新记录时,我都想删除除最新的 10 条记录之外的所有记录。
谢谢!
似乎这会导致大量开销,并且您最好定期通过 cron 修剪数据库,或者如果您真的只需要最后 10 条记录,请找到一种更有效的方式来存储它们。但如果你做不到...
cutoff = PostView.where(:user_id => user_id, :post_id => post_id).
order('created_at DESC').
offset(10).first
PostView.where(:user_id => user_id, :post_id => post_id).
where(['created_at <= ?', cutoff.created_at]).
delete_all
该命令查询所有匹配 user_id 和 post_id 的记录,将这些记录按最新的优先排序,并销毁该集中超过第 10 个最新记录的记录。
PostView.where(user_id: user_id, post_id: post_id).
order('id desc').offset(10).destroy_all
您的问题的另一个解决方案是,您可以更新第 10 个最旧的记录(如果存在),而不是每次都创建一个新的 PostView 记录,否则创建一个新记录。
pv = PostView.first(where: ["user_id = ? AND post_id = ?", user_id, post_id],
order: "id desc", offset: 9) || PostView.new
pv.update_attributes(field1: value1, field2: value2,
created_at: Time.now)