You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Each model's table that is expected to have this behavior must have
a destroyed_at column of type DateTime.
It is recommended that you add an index on the model's destroyed_at column,
so that your database does not have to do a table scan for every query.
Only Postgres' query indexes will be of any benefit:
CREATE INDEX ON users WHERE destroyed_at IS NULL;
CREATE INDEX ON users WHERE destroyed_at IS NOT NULL;
Usage
Allows you to "destroy" an object without deleting the record or
associated records.
Destroying
Overides #destroy to set #destroyed_at to the current time on an object. The
default scope of the class is then set to return objects that have not
been destroyed (i.e., have nil for their destroyed_at value).
#destroyed? will be true when your model is destroyed; it will be
false when your model has been restored.
Be careful when destroying models that have dependent: :destroy. This will delete, not destroy, the associated model if
said model does not include DestroyedAt.
Restoring
When you'd like to "restore" a record, call the #restore method on
the instance. This will set its #destroyed_at value to nil, thereby
including it in the default scope of the class again.
To include this functionality on has_many through relationships,
be sure to include DestroyedAt on the through model, as well as the
parent model.
When you include the DestroyedAt module, it sets a default scope of
where(destroyed_at: nil). It also defines a scope called .destroyed
which removes the default scope and finds the records of a relation
where.not(destroyed_at: nil). This is different than calling unscoped
on the class/relation. Where unscoped will remove all scoping from a
relation, .destroyed only removes the default scope generated by the
DestroyedAt module, making it safe to call on relations.
Callbacks
before_restore, after_restore and around_restore callbacks are added to your
model. They work similarly to the before_destroy, after_destroy and around_restore
callbacks.
classUser < ActiveRecord::Basebefore_restore:before_restore_actionafter_restore:after_restore_actionaround_restore:around_restore_actionprivatedefbefore_restore_action
...
enddefafter_restore_action
...
enddefaround_restore_action# before aroundyield# restoring...# after aroundend
Validations
If you are using the uniqueness validator you will need to run it as:
Rails will by default not include default_scopes when querying for uniqueness. Rather than monkey
patching the validator we believe this is the best solution.