Mongoid document Time to live

Is there a way to set a life time for a document, and then it will be destroyed. I want to create guest users that are temporary for each session, so the document is automatically deleted after a week.

+5
source share
2 answers

MongoDB (version 2.2 and higher) actually has a special index type that allows you to specify TTL in the document (see http://docs.mongodb.org/manual/tutorial/expire-data/ ). The database deletes expired documents for you - there is no need to complete cron jobs or anything else.

Mongoid supports this function as follows:

index({created_at: 1}, {expire_after_seconds: 1.week})

created_at /. Mongoid::Timestamps , .

UPDATE:

, /, . . :

# Special date/time field to base expirations on.
field :expirable_created_at, type: Time

# TTL index on the above field.
index({expirable_created_at: 1}, {expire_after_seconds: 1.week})

# Callback to set `expirable_created_at` only for guest roles.
before_create :set_expire, if: "role == :guest"
def set_expire
  self.expirable_created_at = Time.now
  return true
end
+20

include Mongoid::Timestamps .

-, cron - , ( , , https://github.com/daddye/foreverb)

,

if model.created_at > 1.week.ago
  model.destroy
end
0

All Articles