如何在Rails中自动从数据库中删除记录

Kad*_*ile 2 database ruby-on-rails

我有一个名为products的rails表设置,并且一切正常,假设我要在创建后3周自动删除记录,如何处理代码

我的产品数据库如下

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
Run Code Online (Sandbox Code Playgroud)

egy*_*ado 5

如何处理此任务有不同的方法。检查以下2个选项。

选项1- 每当宝石

您可以使用每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
Run Code Online (Sandbox Code Playgroud)

选项2- SidekickSidetiq宝石

# in app/workers/clean_posts.rb
class CleanPosts
  include Sidekiq::Worker
  include Sidetiq::Schedulable

  recurrence { monthly }

  def perform
    Post.recent.destroy_all
  end
end
Run Code Online (Sandbox Code Playgroud)

# /models/post.rb
class Post < ApplicationRecord
  scope :recent, -> { where('created_at >= :thirty_days_ago', thiryty_days_ago: Time.now - 30.days) }
end
Run Code Online (Sandbox Code Playgroud)

由于Ruby是关于美的,所以将where子句移到模型中,在哪里可以重用它。

这些选项将从数据库中删除旧帖子,并且您的应用程序将不再访问它们。