如何在Rails中自动从数据库中删除记录 [英] how to automatically delete a record from the database in rails
问题描述
我有一个名为products的rails表设置,并且一切运行良好,假设我想在创建后3周自动删除一条记录,如何处理代码
i have a rails table setup called products and its all working well, lets assume i want to auto delete a record 3 weeks after creation how do go about the code
我的产品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个选项。
There are different ways on how to handle this task. Check 2 options below.
选项1-无论何时 gem
Option 1 - whenever gem
您可以使用每30天运行一次的任务来设置任务。
You would setup a task using whenever which runs for example every 30 days.
1-生成如下任务:
rails g任务栏delete_30_days_old
2-在应用程序中创建一个红宝石文件
2- Create a ruby file in your application
# 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
Option 2 - sidekick and Sidetiq gems
# 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子句移到模型中,在哪里可以重复使用。
Since Ruby is about beauty, move the where clause to your model, where can reuse it.
这些选项将从数据库中删除旧帖子并且您的应用程序将无法再访问它们。
These options will remove old posts from your DB and they will no longer be accessible by your application.
这篇关于如何在Rails中自动从数据库中删除记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!