2

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 product db is as follows

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
4

4 に答える 4

3

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

于 2013-06-12T06:42:31.150 に答える
3

毎日特定の時間に実行する必要がある cron ジョブを作成する必要があります。Cron ジョブを設定するには、Gem WHENEVERを使用できます

そして、クエリは次のようになります

Product.where("created_at <= ?", Time.now - 3.weeks).destroy_all
于 2013-06-12T06:14:18.927 に答える
1

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

于 2013-06-12T05:58:22.360 に答える