如何在rails中自动从数据库中删除记录
我有一个名为products的rails表设置,它的运行良好,让我们假设我想在创建3周后自动删除一条记录怎么去代码
我的产品db如下
class Products < ActiveRecord::Migration def change create_table :products do |t| t.text :description t.string :price t.string :name t.string :contact t.attachment :photo t.string :slug t.integer :user_id t.timestamps end add_index :products, :user_id end end
如何处理此任务有不同的方法。 检查以下2个选项。
选项1 – 每当gem
您可以使用每30天运行一次的任务来设置任务。
1-生成如下任务:
rails g task posts delete_30_days_old
2-在应用程序中创建ruby文件
# lib/tasks/delete_old_records.rb namespace :posts do desc "Delete records older than 30 days" task delete_30_days_old: :environment do Post.where(['created_at < ?', 30.days.ago]).destroy_all end end
选项2 - sidekick和Sidetiqgem
# in app/workers/clean_posts.rb class CleanPosts include Sidekiq::Worker include Sidetiq::Schedulable recurrence { monthly } def perform Post.recent.destroy_all end end
和
# /models/post.rb class Post < ApplicationRecord scope :recent, -> { where('created_at >= :thirty_days_ago', thiryty_days_ago: Time.now - 30.days) } end
由于Ruby是关于美的,所以将where子句移动到您的模型,在那里可以重用它。
这些选项将从您的数据库中删除旧post,您的应用程序将无法再访问它们。
如果您想自动执行某项操作,则应在应用中使用cron job。 我有一个使用发条gem的应用程序安排在背景上的一些过程。
一步步 :
把它放在你的Gemfile上
gem 'clockwork' gem 'foreman'
在文件夹app
上创建文件clock.rb
require './config/boot' require './config/environment' require 'clockwork' module Clockwork every(1.day, 'delete.product', :at => '00:00') { Product.where("created_at >= ?", 3.week.ago.utc).destroy_all } end
运行测试发条
clockwork app/clock.rb
例如,这是我的应用程序使用clockwork自动删除用户每隔30.seconds:
C:\Sites\multiple>clockwork app/clock.rb I, [2013-06-12T13:36:14.380239 #2356] INFO -- : Starting clock for 1 events: [ delete.user ] I, [2013-06-12T13:36:14.380239 #2356] INFO -- : Triggering 'delete.user' I, [2013-06-12T13:36:44.784978 #2356] INFO -- : Triggering 'delete.user'
或者如果你想在应用程序中运行发条,你使用工头冷看起来像:
foreman start
注意 :运行工头你应该在你的机器上安装工头
您需要创建一个cron作业,该作业必须在特定时间每天运行。 要设置Cron作业,您可以使用Gem WHENEVER
查询应该是这样的
Product.where("created_at <= ?", Time.now - 3.weeks).destroy_all
创建rake任务并定期运行该rake任务。 就像是:
delete_old_products.rake:
task delete_old_products: :environment do Product.where("created_at <= ?", Time.now - 3.weeks).each do |product| product.destroy end end
您可以使用rake delete_old_products
从命令行运行该命令
- rails – 在用户订购时created_at,是否应该向表中添加索引?
- 从validation错误消息中删除字段名称
- 对于使用哪种Prototype助手感到困惑
- 使用LDAP / AD登录身份validation时如果使用AD记录不存在用户行,如何创建用户行
- “identify”命令无法识别图像文件。 (Heroku的)
- 如何使用/围绕Gmail的SMTP出站发送限制?
- 获取在控制器/视图中工作的方法在模型中运行,Ruby on Rails
- 如何在rails中的function测试中启用页面缓存?
- Rails教程sample_app在Heroku中失败,带有log:ActionController :: RoutingError(没有路由匹配“/ about”):