how to automatically delete a record from the database in rails

后端 未结 4 471
悲哀的现实
悲哀的现实 2021-02-04 22:35

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

my produc

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 22:54

    There are different ways on how to handle this task. Check 2 options below.

    Option 1 - whenever gem

    You would setup a task using whenever which runs for example every 30 days.

    1- Generate task as following:

    rails g task posts delete_30_days_old

    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
    

    and

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

    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.

提交回复
热议问题