how to automatically delete a record from the database in rails

后端 未结 4 475
悲哀的现实
悲哀的现实 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:58

    If you want automatically an action, you should use cron job in your app. I have an app using clockwork gem for schedule some process on background.

    Step by step :

    Put this on your Gemfile

    gem 'clockwork'
    gem 'foreman'
    

    Create file clock.rb on folder app

    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
    

    Running test clockwork

    clockwork app/clock.rb
    

    Example, this is my app using clockwork with delete automatically user every 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'
    

    Or If you want running clockwork with the app, you cold using foreman looks like :

    foreman start
    

    Note : running foreman you should install foreman on your machine

提交回复
热议问题