Convenient removal of obsolete records for ActiveRecord models.
Add this line to your application's Gemfile:
gem 'activerecord-prunable'
And then execute:
$ bundle
Or install it yourself as:
$ gem install activerecord-prunable
1. Include the Prunable
module in the ActiveRecord model which needs to be pruned.
2. Define the :prunable
scope which returns records to prune.
class Notification < ApplicationRecord
include ActiveRecord::Prunable
scope :prunable, -> { where("created_at > ?", 1.month.ago) }
# You can also set type of removing records (:destroy or :delete).
# By default it's :destroy
prune_method :delete
end
or use one of the prune_after
, prune_created_after
, prune_updated_after
methods
class Notification < ApplicationRecord
include ActiveRecord::Prunable
prune_after 7.days
end
prune_after
is an alias for prune_created_after
prune_created_after(TTL)
defines where('created_at < ?', current_time - TTL)
prunable scope
prune_updated_after(TTL)
defines where('updated_at < ?', current_time - TTL)
prunable scope
3. Add a Prunable.prune!
call to a periodic task.
Example:
# clockwork configuration file
every(1.day, 'models.prune', at: '04:20', thread: true) { Prunable.prune! }
You can also inject current time Prunable.prune!(current_time: Time.current)
Pruning a single model:
SomeModel.prune!
Pruning multiple models:
Note that the Prunable.prune!
calls Rails.application.eager_load!
. It can decrease free memory size.
Prunable.prune!(SomeModel, AnotherModel)
Set default method of pruning (:destroy or :delete):
Prunable.prune!(prune_method: :delete)
Call :prunable
scope with params:
Prunable.prune!(params: [:foo, :bar])
Getting an array of all the models which include ActiveRecord::Prunable
:
Prunable.models
Pruning all models which include ActiveRecord::Prunable
:
Prunable.prune!